id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
10,600
gravitational/trace
errors.go
IsRetryError
func IsRetryError(e error) bool { type ad interface { IsRetryError() bool } _, ok := Unwrap(e).(ad) return ok }
go
func IsRetryError(e error) bool { type ad interface { IsRetryError() bool } _, ok := Unwrap(e).(ad) return ok }
[ "func", "IsRetryError", "(", "e", "error", ")", "bool", "{", "type", "ad", "interface", "{", "IsRetryError", "(", ")", "bool", "\n", "}", "\n", "_", ",", "ok", ":=", "Unwrap", "(", "e", ")", ".", "(", "ad", ")", "\n", "return", "ok", "\n", "}" ]
// IsRetryError returns whether this error is of ConnectionProblemError
[ "IsRetryError", "returns", "whether", "this", "error", "is", "of", "ConnectionProblemError" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L479-L485
10,601
gravitational/trace
log.go
IsTerminal
func IsTerminal(w io.Writer) bool { switch v := w.(type) { case *os.File: return terminal.IsTerminal(int(v.Fd())) default: return false } }
go
func IsTerminal(w io.Writer) bool { switch v := w.(type) { case *os.File: return terminal.IsTerminal(int(v.Fd())) default: return false } }
[ "func", "IsTerminal", "(", "w", "io", ".", "Writer", ")", "bool", "{", "switch", "v", ":=", "w", ".", "(", "type", ")", "{", "case", "*", "os", ".", "File", ":", "return", "terminal", ".", "IsTerminal", "(", "int", "(", "v", ".", "Fd", "(", ")", ")", ")", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsTerminal checks whether writer is a terminal
[ "IsTerminal", "checks", "whether", "writer", "is", "a", "terminal" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/log.go#L57-L64
10,602
gravitational/trace
log.go
Format
func (tf *TextFormatter) Format(e *log.Entry) (data []byte, err error) { defer func() { if r := recover(); r != nil { data = append([]byte("panic in log formatter\n"), rundebug.Stack()...) return } }() var file string if cursor := findFrame(); cursor != nil { t := newTraceFromFrames(*cursor, nil) file = t.Loc() } w := &writer{} // time if !tf.DisableTimestamp { w.writeField(e.Time.Format(time.RFC3339), noColor) } // level color := noColor if tf.EnableColors { switch e.Level { case log.DebugLevel: color = gray case log.WarnLevel: color = yellow case log.ErrorLevel, log.FatalLevel, log.PanicLevel: color = red default: color = blue } } w.writeField(strings.ToUpper(padMax(e.Level.String(), DefaultLevelPadding)), color) // always output the component field if available padding := DefaultComponentPadding if tf.ComponentPadding != 0 { padding = tf.ComponentPadding } if w.Len() > 0 { w.WriteByte(' ') } value := e.Data[Component] var component string if reflect.ValueOf(value).IsValid() { component = fmt.Sprintf("[%v]", value) } component = strings.ToUpper(padMax(component, padding)) if component[len(component)-1] != ' ' { component = component[:len(component)-1] + "]" } w.WriteString(component) // message if e.Message != "" { w.writeField(e.Message, noColor) } // rest of the fields if len(e.Data) > 0 { w.writeMap(e.Data) } // file, if present, always last if file != "" { w.writeField(file, noColor) } w.WriteByte('\n') data = w.Bytes() return }
go
func (tf *TextFormatter) Format(e *log.Entry) (data []byte, err error) { defer func() { if r := recover(); r != nil { data = append([]byte("panic in log formatter\n"), rundebug.Stack()...) return } }() var file string if cursor := findFrame(); cursor != nil { t := newTraceFromFrames(*cursor, nil) file = t.Loc() } w := &writer{} // time if !tf.DisableTimestamp { w.writeField(e.Time.Format(time.RFC3339), noColor) } // level color := noColor if tf.EnableColors { switch e.Level { case log.DebugLevel: color = gray case log.WarnLevel: color = yellow case log.ErrorLevel, log.FatalLevel, log.PanicLevel: color = red default: color = blue } } w.writeField(strings.ToUpper(padMax(e.Level.String(), DefaultLevelPadding)), color) // always output the component field if available padding := DefaultComponentPadding if tf.ComponentPadding != 0 { padding = tf.ComponentPadding } if w.Len() > 0 { w.WriteByte(' ') } value := e.Data[Component] var component string if reflect.ValueOf(value).IsValid() { component = fmt.Sprintf("[%v]", value) } component = strings.ToUpper(padMax(component, padding)) if component[len(component)-1] != ' ' { component = component[:len(component)-1] + "]" } w.WriteString(component) // message if e.Message != "" { w.writeField(e.Message, noColor) } // rest of the fields if len(e.Data) > 0 { w.writeMap(e.Data) } // file, if present, always last if file != "" { w.writeField(file, noColor) } w.WriteByte('\n') data = w.Bytes() return }
[ "func", "(", "tf", "*", "TextFormatter", ")", "Format", "(", "e", "*", "log", ".", "Entry", ")", "(", "data", "[", "]", "byte", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "data", "=", "append", "(", "[", "]", "byte", "(", "\"", "\\n", "\"", ")", ",", "rundebug", ".", "Stack", "(", ")", "...", ")", "\n", "return", "\n", "}", "\n", "}", "(", ")", "\n\n", "var", "file", "string", "\n", "if", "cursor", ":=", "findFrame", "(", ")", ";", "cursor", "!=", "nil", "{", "t", ":=", "newTraceFromFrames", "(", "*", "cursor", ",", "nil", ")", "\n", "file", "=", "t", ".", "Loc", "(", ")", "\n", "}", "\n\n", "w", ":=", "&", "writer", "{", "}", "\n\n", "// time", "if", "!", "tf", ".", "DisableTimestamp", "{", "w", ".", "writeField", "(", "e", ".", "Time", ".", "Format", "(", "time", ".", "RFC3339", ")", ",", "noColor", ")", "\n", "}", "\n\n", "// level", "color", ":=", "noColor", "\n", "if", "tf", ".", "EnableColors", "{", "switch", "e", ".", "Level", "{", "case", "log", ".", "DebugLevel", ":", "color", "=", "gray", "\n", "case", "log", ".", "WarnLevel", ":", "color", "=", "yellow", "\n", "case", "log", ".", "ErrorLevel", ",", "log", ".", "FatalLevel", ",", "log", ".", "PanicLevel", ":", "color", "=", "red", "\n", "default", ":", "color", "=", "blue", "\n", "}", "\n", "}", "\n", "w", ".", "writeField", "(", "strings", ".", "ToUpper", "(", "padMax", "(", "e", ".", "Level", ".", "String", "(", ")", ",", "DefaultLevelPadding", ")", ")", ",", "color", ")", "\n\n", "// always output the component field if available", "padding", ":=", "DefaultComponentPadding", "\n", "if", "tf", ".", "ComponentPadding", "!=", "0", "{", "padding", "=", "tf", ".", "ComponentPadding", "\n", "}", "\n", "if", "w", ".", "Len", "(", ")", ">", "0", "{", "w", ".", "WriteByte", "(", "' '", ")", "\n", "}", "\n", "value", ":=", "e", ".", "Data", "[", "Component", "]", "\n", "var", "component", "string", "\n", "if", "reflect", ".", "ValueOf", "(", "value", ")", ".", "IsValid", "(", ")", "{", "component", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "value", ")", "\n", "}", "\n", "component", "=", "strings", ".", "ToUpper", "(", "padMax", "(", "component", ",", "padding", ")", ")", "\n", "if", "component", "[", "len", "(", "component", ")", "-", "1", "]", "!=", "' '", "{", "component", "=", "component", "[", ":", "len", "(", "component", ")", "-", "1", "]", "+", "\"", "\"", "\n", "}", "\n", "w", ".", "WriteString", "(", "component", ")", "\n\n", "// message", "if", "e", ".", "Message", "!=", "\"", "\"", "{", "w", ".", "writeField", "(", "e", ".", "Message", ",", "noColor", ")", "\n", "}", "\n\n", "// rest of the fields", "if", "len", "(", "e", ".", "Data", ")", ">", "0", "{", "w", ".", "writeMap", "(", "e", ".", "Data", ")", "\n", "}", "\n\n", "// file, if present, always last", "if", "file", "!=", "\"", "\"", "{", "w", ".", "writeField", "(", "file", ",", "noColor", ")", "\n", "}", "\n\n", "w", ".", "WriteByte", "(", "'\\n'", ")", "\n", "data", "=", "w", ".", "Bytes", "(", ")", "\n", "return", "\n", "}" ]
// Format implements logrus.Formatter interface and adds file and line
[ "Format", "implements", "logrus", ".", "Formatter", "interface", "and", "adds", "file", "and", "line" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/log.go#L80-L154
10,603
gravitational/trace
log.go
Format
func (j *JSONFormatter) Format(e *log.Entry) ([]byte, error) { if cursor := findFrame(); cursor != nil { t := newTraceFromFrames(*cursor, nil) new := e.WithFields(log.Fields{ FileField: t.Loc(), FunctionField: t.FuncName(), }) new.Time = e.Time new.Level = e.Level new.Message = e.Message e = new } return j.JSONFormatter.Format(e) }
go
func (j *JSONFormatter) Format(e *log.Entry) ([]byte, error) { if cursor := findFrame(); cursor != nil { t := newTraceFromFrames(*cursor, nil) new := e.WithFields(log.Fields{ FileField: t.Loc(), FunctionField: t.FuncName(), }) new.Time = e.Time new.Level = e.Level new.Message = e.Message e = new } return j.JSONFormatter.Format(e) }
[ "func", "(", "j", "*", "JSONFormatter", ")", "Format", "(", "e", "*", "log", ".", "Entry", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "cursor", ":=", "findFrame", "(", ")", ";", "cursor", "!=", "nil", "{", "t", ":=", "newTraceFromFrames", "(", "*", "cursor", ",", "nil", ")", "\n", "new", ":=", "e", ".", "WithFields", "(", "log", ".", "Fields", "{", "FileField", ":", "t", ".", "Loc", "(", ")", ",", "FunctionField", ":", "t", ".", "FuncName", "(", ")", ",", "}", ")", "\n", "new", ".", "Time", "=", "e", ".", "Time", "\n", "new", ".", "Level", "=", "e", ".", "Level", "\n", "new", ".", "Message", "=", "e", ".", "Message", "\n", "e", "=", "new", "\n", "}", "\n", "return", "j", ".", "JSONFormatter", ".", "Format", "(", "e", ")", "\n", "}" ]
// Format implements logrus.Formatter interface
[ "Format", "implements", "logrus", ".", "Formatter", "interface" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/log.go#L163-L176
10,604
gravitational/trace
log.go
findFrame
func findFrame() *frameCursor { var buf [32]uintptr // Skip enough frames to start at user code. // This number is a mere hint to the following loop // to start as close to user code as possible and getting it right is not mandatory. // The skip count might need to get updated if the call to findFrame is // moved up/down the call stack n := runtime.Callers(4, buf[:]) pcs := buf[:n] frames := runtime.CallersFrames(pcs) for i := 0; i < n; i++ { frame, _ := frames.Next() if !frameIgnorePattern.MatchString(frame.File) { return &frameCursor{ current: &frame, rest: frames, n: n, } } } return nil }
go
func findFrame() *frameCursor { var buf [32]uintptr // Skip enough frames to start at user code. // This number is a mere hint to the following loop // to start as close to user code as possible and getting it right is not mandatory. // The skip count might need to get updated if the call to findFrame is // moved up/down the call stack n := runtime.Callers(4, buf[:]) pcs := buf[:n] frames := runtime.CallersFrames(pcs) for i := 0; i < n; i++ { frame, _ := frames.Next() if !frameIgnorePattern.MatchString(frame.File) { return &frameCursor{ current: &frame, rest: frames, n: n, } } } return nil }
[ "func", "findFrame", "(", ")", "*", "frameCursor", "{", "var", "buf", "[", "32", "]", "uintptr", "\n", "// Skip enough frames to start at user code.", "// This number is a mere hint to the following loop", "// to start as close to user code as possible and getting it right is not mandatory.", "// The skip count might need to get updated if the call to findFrame is", "// moved up/down the call stack", "n", ":=", "runtime", ".", "Callers", "(", "4", ",", "buf", "[", ":", "]", ")", "\n", "pcs", ":=", "buf", "[", ":", "n", "]", "\n", "frames", ":=", "runtime", ".", "CallersFrames", "(", "pcs", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "frame", ",", "_", ":=", "frames", ".", "Next", "(", ")", "\n", "if", "!", "frameIgnorePattern", ".", "MatchString", "(", "frame", ".", "File", ")", "{", "return", "&", "frameCursor", "{", "current", ":", "&", "frame", ",", "rest", ":", "frames", ",", "n", ":", "n", ",", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// findFrames positions the stack pointer to the first // function that does not match the frameIngorePattern // and returns the rest of the stack frames
[ "findFrames", "positions", "the", "stack", "pointer", "to", "the", "first", "function", "that", "does", "not", "match", "the", "frameIngorePattern", "and", "returns", "the", "rest", "of", "the", "stack", "frames" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/log.go#L183-L204
10,605
gravitational/trace
trace.go
Wrap
func Wrap(err error, args ...interface{}) Error { if len(args) > 0 { format := args[0] args = args[1:] return WrapWithMessage(err, format, args...) } return wrapWithDepth(err, 2) }
go
func Wrap(err error, args ...interface{}) Error { if len(args) > 0 { format := args[0] args = args[1:] return WrapWithMessage(err, format, args...) } return wrapWithDepth(err, 2) }
[ "func", "Wrap", "(", "err", "error", ",", "args", "...", "interface", "{", "}", ")", "Error", "{", "if", "len", "(", "args", ")", ">", "0", "{", "format", ":=", "args", "[", "0", "]", "\n", "args", "=", "args", "[", "1", ":", "]", "\n", "return", "WrapWithMessage", "(", "err", ",", "format", ",", "args", "...", ")", "\n", "}", "\n", "return", "wrapWithDepth", "(", "err", ",", "2", ")", "\n", "}" ]
// Wrap takes the original error and wraps it into the Trace struct // memorizing the context of the error.
[ "Wrap", "takes", "the", "original", "error", "and", "wraps", "it", "into", "the", "Trace", "struct", "memorizing", "the", "context", "of", "the", "error", "." ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L50-L57
10,606
gravitational/trace
trace.go
Unwrap
func Unwrap(err error) error { if terr, ok := err.(Error); ok { return terr.OrigError() } return err }
go
func Unwrap(err error) error { if terr, ok := err.(Error); ok { return terr.OrigError() } return err }
[ "func", "Unwrap", "(", "err", "error", ")", "error", "{", "if", "terr", ",", "ok", ":=", "err", ".", "(", "Error", ")", ";", "ok", "{", "return", "terr", ".", "OrigError", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Unwrap unwraps error to it's original error
[ "Unwrap", "unwraps", "error", "to", "it", "s", "original", "error" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L60-L65
10,607
gravitational/trace
trace.go
UserMessage
func UserMessage(err error) string { if err == nil { return "" } if wrap, ok := err.(Error); ok { return wrap.UserMessage() } return err.Error() }
go
func UserMessage(err error) string { if err == nil { return "" } if wrap, ok := err.(Error); ok { return wrap.UserMessage() } return err.Error() }
[ "func", "UserMessage", "(", "err", "error", ")", "string", "{", "if", "err", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "if", "wrap", ",", "ok", ":=", "err", ".", "(", "Error", ")", ";", "ok", "{", "return", "wrap", ".", "UserMessage", "(", ")", "\n", "}", "\n", "return", "err", ".", "Error", "(", ")", "\n", "}" ]
// UserMessage returns user-friendly part of the error
[ "UserMessage", "returns", "user", "-", "friendly", "part", "of", "the", "error" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L68-L76
10,608
gravitational/trace
trace.go
DebugReport
func DebugReport(err error) string { if err == nil { return "" } if wrap, ok := err.(Error); ok { return wrap.DebugReport() } return err.Error() }
go
func DebugReport(err error) string { if err == nil { return "" } if wrap, ok := err.(Error); ok { return wrap.DebugReport() } return err.Error() }
[ "func", "DebugReport", "(", "err", "error", ")", "string", "{", "if", "err", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "if", "wrap", ",", "ok", ":=", "err", ".", "(", "Error", ")", ";", "ok", "{", "return", "wrap", ".", "DebugReport", "(", ")", "\n", "}", "\n", "return", "err", ".", "Error", "(", ")", "\n", "}" ]
// DebugReport returns debug report with all known information // about the error including stack trace if it was captured
[ "DebugReport", "returns", "debug", "report", "with", "all", "known", "information", "about", "the", "error", "including", "stack", "trace", "if", "it", "was", "captured" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L80-L88
10,609
gravitational/trace
trace.go
WrapWithMessage
func WrapWithMessage(err error, message interface{}, args ...interface{}) Error { trace := wrapWithDepth(err, 3) if trace != nil { trace.AddUserMessage(message, args...) } return trace }
go
func WrapWithMessage(err error, message interface{}, args ...interface{}) Error { trace := wrapWithDepth(err, 3) if trace != nil { trace.AddUserMessage(message, args...) } return trace }
[ "func", "WrapWithMessage", "(", "err", "error", ",", "message", "interface", "{", "}", ",", "args", "...", "interface", "{", "}", ")", "Error", "{", "trace", ":=", "wrapWithDepth", "(", "err", ",", "3", ")", "\n", "if", "trace", "!=", "nil", "{", "trace", ".", "AddUserMessage", "(", "message", ",", "args", "...", ")", "\n", "}", "\n", "return", "trace", "\n", "}" ]
// WrapWithMessage wraps the original error into Error and adds user message if any
[ "WrapWithMessage", "wraps", "the", "original", "error", "into", "Error", "and", "adds", "user", "message", "if", "any" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L91-L97
10,610
gravitational/trace
trace.go
Errorf
func Errorf(format string, args ...interface{}) (err error) { err = fmt.Errorf(format, args...) trace := wrapWithDepth(err, 2) trace.AddUserMessage(format, args...) return trace }
go
func Errorf(format string, args ...interface{}) (err error) { err = fmt.Errorf(format, args...) trace := wrapWithDepth(err, 2) trace.AddUserMessage(format, args...) return trace }
[ "func", "Errorf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "err", "=", "fmt", ".", "Errorf", "(", "format", ",", "args", "...", ")", "\n", "trace", ":=", "wrapWithDepth", "(", "err", ",", "2", ")", "\n", "trace", ".", "AddUserMessage", "(", "format", ",", "args", "...", ")", "\n", "return", "trace", "\n", "}" ]
// Errorf is similar to fmt.Errorf except that it captures // more information about the origin of error, such as // callee, line number and function that simplifies debugging
[ "Errorf", "is", "similar", "to", "fmt", ".", "Errorf", "except", "that", "it", "captures", "more", "information", "about", "the", "origin", "of", "error", "such", "as", "callee", "line", "number", "and", "function", "that", "simplifies", "debugging" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L116-L121
10,611
gravitational/trace
trace.go
Fatalf
func Fatalf(format string, args ...interface{}) error { if IsDebug() { panic(fmt.Sprintf(format, args...)) } else { return Errorf(format, args...) } }
go
func Fatalf(format string, args ...interface{}) error { if IsDebug() { panic(fmt.Sprintf(format, args...)) } else { return Errorf(format, args...) } }
[ "func", "Fatalf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "if", "IsDebug", "(", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", ")", "\n", "}", "else", "{", "return", "Errorf", "(", "format", ",", "args", "...", ")", "\n", "}", "\n", "}" ]
// Fatalf - If debug is false Fatalf calls Errorf. If debug is // true Fatalf calls panic
[ "Fatalf", "-", "If", "debug", "is", "false", "Fatalf", "calls", "Errorf", ".", "If", "debug", "is", "true", "Fatalf", "calls", "panic" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L125-L131
10,612
gravitational/trace
trace.go
FuncName
func (s Traces) FuncName() string { if len(s) == 0 { return "" } fn := filepath.ToSlash(s[0].Func) idx := strings.LastIndex(fn, "/") if idx == -1 || idx == len(fn)-1 { return fn } return fn[idx+1:] }
go
func (s Traces) FuncName() string { if len(s) == 0 { return "" } fn := filepath.ToSlash(s[0].Func) idx := strings.LastIndex(fn, "/") if idx == -1 || idx == len(fn)-1 { return fn } return fn[idx+1:] }
[ "func", "(", "s", "Traces", ")", "FuncName", "(", ")", "string", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "fn", ":=", "filepath", ".", "ToSlash", "(", "s", "[", "0", "]", ".", "Func", ")", "\n", "idx", ":=", "strings", ".", "LastIndex", "(", "fn", ",", "\"", "\"", ")", "\n", "if", "idx", "==", "-", "1", "||", "idx", "==", "len", "(", "fn", ")", "-", "1", "{", "return", "fn", "\n", "}", "\n", "return", "fn", "[", "idx", "+", "1", ":", "]", "\n", "}" ]
// Func returns just function name
[ "Func", "returns", "just", "function", "name" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L198-L208
10,613
gravitational/trace
trace.go
String
func (s Traces) String() string { if len(s) == 0 { return "" } out := make([]string, len(s)) for i, t := range s { out[i] = fmt.Sprintf("\t%v:%v %v", t.Path, t.Line, t.Func) } return strings.Join(out, "\n") }
go
func (s Traces) String() string { if len(s) == 0 { return "" } out := make([]string, len(s)) for i, t := range s { out[i] = fmt.Sprintf("\t%v:%v %v", t.Path, t.Line, t.Func) } return strings.Join(out, "\n") }
[ "func", "(", "s", "Traces", ")", "String", "(", ")", "string", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "s", ")", ")", "\n", "for", "i", ",", "t", ":=", "range", "s", "{", "out", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\\t", "\"", ",", "t", ".", "Path", ",", "t", ".", "Line", ",", "t", ".", "Func", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "out", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// String returns debug-friendly representaton of trace stack
[ "String", "returns", "debug", "-", "friendly", "representaton", "of", "trace", "stack" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L219-L228
10,614
gravitational/trace
trace.go
String
func (t *Trace) String() string { dir, file := filepath.Split(t.Path) dirs := strings.Split(filepath.ToSlash(filepath.Clean(dir)), "/") if len(dirs) != 0 { file = filepath.Join(dirs[len(dirs)-1], file) } return fmt.Sprintf("%v:%v", file, t.Line) }
go
func (t *Trace) String() string { dir, file := filepath.Split(t.Path) dirs := strings.Split(filepath.ToSlash(filepath.Clean(dir)), "/") if len(dirs) != 0 { file = filepath.Join(dirs[len(dirs)-1], file) } return fmt.Sprintf("%v:%v", file, t.Line) }
[ "func", "(", "t", "*", "Trace", ")", "String", "(", ")", "string", "{", "dir", ",", "file", ":=", "filepath", ".", "Split", "(", "t", ".", "Path", ")", "\n", "dirs", ":=", "strings", ".", "Split", "(", "filepath", ".", "ToSlash", "(", "filepath", ".", "Clean", "(", "dir", ")", ")", ",", "\"", "\"", ")", "\n", "if", "len", "(", "dirs", ")", "!=", "0", "{", "file", "=", "filepath", ".", "Join", "(", "dirs", "[", "len", "(", "dirs", ")", "-", "1", "]", ",", "file", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "file", ",", "t", ".", "Line", ")", "\n", "}" ]
// String returns debug-friendly representation of this trace
[ "String", "returns", "debug", "-", "friendly", "representation", "of", "this", "trace" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L241-L248
10,615
gravitational/trace
trace.go
AddUserMessage
func (e *TraceErr) AddUserMessage(formatArg interface{}, rest ...interface{}) { newMessage := fmt.Sprintf(fmt.Sprintf("%v", formatArg), rest...) if len(e.Message) == 0 { e.Message = newMessage } else { e.Message = strings.Join([]string{e.Message, newMessage}, ", ") } }
go
func (e *TraceErr) AddUserMessage(formatArg interface{}, rest ...interface{}) { newMessage := fmt.Sprintf(fmt.Sprintf("%v", formatArg), rest...) if len(e.Message) == 0 { e.Message = newMessage } else { e.Message = strings.Join([]string{e.Message, newMessage}, ", ") } }
[ "func", "(", "e", "*", "TraceErr", ")", "AddUserMessage", "(", "formatArg", "interface", "{", "}", ",", "rest", "...", "interface", "{", "}", ")", "{", "newMessage", ":=", "fmt", ".", "Sprintf", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "formatArg", ")", ",", "rest", "...", ")", "\n", "if", "len", "(", "e", ".", "Message", ")", "==", "0", "{", "e", ".", "Message", "=", "newMessage", "\n", "}", "else", "{", "e", ".", "Message", "=", "strings", ".", "Join", "(", "[", "]", "string", "{", "e", ".", "Message", ",", "newMessage", "}", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// AddUserMessage adds user-friendly message describing the error nature
[ "AddUserMessage", "adds", "user", "-", "friendly", "message", "describing", "the", "error", "nature" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L265-L272
10,616
gravitational/trace
trace.go
UserMessage
func (e *TraceErr) UserMessage() string { if e.Message != "" { return e.Message } return UserMessage(e.Err) }
go
func (e *TraceErr) UserMessage() string { if e.Message != "" { return e.Message } return UserMessage(e.Err) }
[ "func", "(", "e", "*", "TraceErr", ")", "UserMessage", "(", ")", "string", "{", "if", "e", ".", "Message", "!=", "\"", "\"", "{", "return", "e", ".", "Message", "\n", "}", "\n", "return", "UserMessage", "(", "e", ".", "Err", ")", "\n", "}" ]
// UserMessage returns user-friendly error message
[ "UserMessage", "returns", "user", "-", "friendly", "error", "message" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L275-L280
10,617
gravitational/trace
trace.go
DebugReport
func (e *TraceErr) DebugReport() string { return fmt.Sprintf("\nERROR REPORT:\nOriginal Error: %T %v\nStack Trace:\n%v\nUser Message: %v\n", e.Err, e.Err.Error(), e.Traces.String(), e.Message) }
go
func (e *TraceErr) DebugReport() string { return fmt.Sprintf("\nERROR REPORT:\nOriginal Error: %T %v\nStack Trace:\n%v\nUser Message: %v\n", e.Err, e.Err.Error(), e.Traces.String(), e.Message) }
[ "func", "(", "e", "*", "TraceErr", ")", "DebugReport", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\\n", "\\n", "\\n", "\"", ",", "e", ".", "Err", ",", "e", ".", "Err", ".", "Error", "(", ")", ",", "e", ".", "Traces", ".", "String", "(", ")", ",", "e", ".", "Message", ")", "\n", "}" ]
// DebugReport returns develeoper-friendly error report
[ "DebugReport", "returns", "develeoper", "-", "friendly", "error", "report" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L283-L285
10,618
gravitational/trace
trace.go
OrigError
func (e *TraceErr) OrigError() error { err := e.Err // this is not an endless loop because I'm being // paranoid, this is a safe protection against endless // loops for i := 0; i < maxHops; i++ { newerr, ok := err.(Error) if !ok { break } if newerr.OrigError() != err { err = newerr.OrigError() } } return err }
go
func (e *TraceErr) OrigError() error { err := e.Err // this is not an endless loop because I'm being // paranoid, this is a safe protection against endless // loops for i := 0; i < maxHops; i++ { newerr, ok := err.(Error) if !ok { break } if newerr.OrigError() != err { err = newerr.OrigError() } } return err }
[ "func", "(", "e", "*", "TraceErr", ")", "OrigError", "(", ")", "error", "{", "err", ":=", "e", ".", "Err", "\n", "// this is not an endless loop because I'm being", "// paranoid, this is a safe protection against endless", "// loops", "for", "i", ":=", "0", ";", "i", "<", "maxHops", ";", "i", "++", "{", "newerr", ",", "ok", ":=", "err", ".", "(", "Error", ")", "\n", "if", "!", "ok", "{", "break", "\n", "}", "\n", "if", "newerr", ".", "OrigError", "(", ")", "!=", "err", "{", "err", "=", "newerr", ".", "OrigError", "(", ")", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// OrigError returns original wrapped error
[ "OrigError", "returns", "original", "wrapped", "error" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L293-L308
10,619
gravitational/trace
trace.go
NewAggregate
func NewAggregate(errs ...error) error { // filter out possible nil values var nonNils []error for _, err := range errs { if err != nil { nonNils = append(nonNils, err) } } if len(nonNils) == 0 { return nil } return wrapWithDepth(aggregate(nonNils), 2) }
go
func NewAggregate(errs ...error) error { // filter out possible nil values var nonNils []error for _, err := range errs { if err != nil { nonNils = append(nonNils, err) } } if len(nonNils) == 0 { return nil } return wrapWithDepth(aggregate(nonNils), 2) }
[ "func", "NewAggregate", "(", "errs", "...", "error", ")", "error", "{", "// filter out possible nil values", "var", "nonNils", "[", "]", "error", "\n", "for", "_", ",", "err", ":=", "range", "errs", "{", "if", "err", "!=", "nil", "{", "nonNils", "=", "append", "(", "nonNils", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "nonNils", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "wrapWithDepth", "(", "aggregate", "(", "nonNils", ")", ",", "2", ")", "\n", "}" ]
// NewAggregate creates a new aggregate instance from the specified // list of errors
[ "NewAggregate", "creates", "a", "new", "aggregate", "instance", "from", "the", "specified", "list", "of", "errors" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L342-L354
10,620
gravitational/trace
trace.go
IsAggregate
func IsAggregate(err error) bool { _, ok := Unwrap(err).(Aggregate) return ok }
go
func IsAggregate(err error) bool { _, ok := Unwrap(err).(Aggregate) return ok }
[ "func", "IsAggregate", "(", "err", "error", ")", "bool", "{", "_", ",", "ok", ":=", "Unwrap", "(", "err", ")", ".", "(", "Aggregate", ")", "\n", "return", "ok", "\n", "}" ]
// IsAggregate returns whether this error of Aggregate error type
[ "IsAggregate", "returns", "whether", "this", "error", "of", "Aggregate", "error", "type" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trace.go#L408-L411
10,621
gravitational/trace
udphook.go
NewUDPHook
func NewUDPHook(opts ...UDPOptionSetter) (*UDPHook, error) { f := &UDPHook{} for _, o := range opts { o(f) } if f.Clock == nil { f.Clock = clockwork.NewRealClock() } if f.clientNet == "" { f.clientNet = UDPDefaultNet } if f.clientAddr == "" { f.clientAddr = UDPDefaultAddr } addr, err := net.ResolveUDPAddr(f.clientNet, f.clientAddr) if err != nil { return nil, Wrap(err) } conn, err := net.ListenPacket("udp", ":0") if err != nil { return nil, Wrap(err) } f.addr = addr f.conn = conn.(*net.UDPConn) return f, nil }
go
func NewUDPHook(opts ...UDPOptionSetter) (*UDPHook, error) { f := &UDPHook{} for _, o := range opts { o(f) } if f.Clock == nil { f.Clock = clockwork.NewRealClock() } if f.clientNet == "" { f.clientNet = UDPDefaultNet } if f.clientAddr == "" { f.clientAddr = UDPDefaultAddr } addr, err := net.ResolveUDPAddr(f.clientNet, f.clientAddr) if err != nil { return nil, Wrap(err) } conn, err := net.ListenPacket("udp", ":0") if err != nil { return nil, Wrap(err) } f.addr = addr f.conn = conn.(*net.UDPConn) return f, nil }
[ "func", "NewUDPHook", "(", "opts", "...", "UDPOptionSetter", ")", "(", "*", "UDPHook", ",", "error", ")", "{", "f", ":=", "&", "UDPHook", "{", "}", "\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "f", ")", "\n", "}", "\n", "if", "f", ".", "Clock", "==", "nil", "{", "f", ".", "Clock", "=", "clockwork", ".", "NewRealClock", "(", ")", "\n", "}", "\n", "if", "f", ".", "clientNet", "==", "\"", "\"", "{", "f", ".", "clientNet", "=", "UDPDefaultNet", "\n", "}", "\n", "if", "f", ".", "clientAddr", "==", "\"", "\"", "{", "f", ".", "clientAddr", "=", "UDPDefaultAddr", "\n", "}", "\n", "addr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "f", ".", "clientNet", ",", "f", ".", "clientAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "Wrap", "(", "err", ")", "\n", "}", "\n", "conn", ",", "err", ":=", "net", ".", "ListenPacket", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "Wrap", "(", "err", ")", "\n", "}", "\n", "f", ".", "addr", "=", "addr", "\n", "f", ".", "conn", "=", "conn", ".", "(", "*", "net", ".", "UDPConn", ")", "\n", "return", "f", ",", "nil", "\n", "}" ]
// NewUDPHook returns logrus-compatible hook that sends data to UDP socket
[ "NewUDPHook", "returns", "logrus", "-", "compatible", "hook", "that", "sends", "data", "to", "UDP", "socket" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/udphook.go#L23-L48
10,622
gravitational/trace
udphook.go
Fire
func (elk *UDPHook) Fire(e *log.Entry) error { // Make a copy to safely modify entry := e.WithFields(nil) if cursor := findFrame(); cursor != nil { t := newTraceFromFrames(*cursor, nil) entry.Data[FileField] = t.String() entry.Data[FunctionField] = t.Func() } data, err := json.Marshal(Frame{ Time: elk.Clock.Now().UTC(), Type: "trace", Entry: entry.Data, Message: entry.Message, Level: entry.Level.String(), }) if err != nil { return Wrap(err) } conn, err := net.ListenPacket("udp", ":0") if err != nil { return Wrap(err) } defer conn.Close() resolvedAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:5000") if err != nil { return Wrap(err) } _, err = (conn.(*net.UDPConn)).WriteToUDP(data, resolvedAddr) return Wrap(err) }
go
func (elk *UDPHook) Fire(e *log.Entry) error { // Make a copy to safely modify entry := e.WithFields(nil) if cursor := findFrame(); cursor != nil { t := newTraceFromFrames(*cursor, nil) entry.Data[FileField] = t.String() entry.Data[FunctionField] = t.Func() } data, err := json.Marshal(Frame{ Time: elk.Clock.Now().UTC(), Type: "trace", Entry: entry.Data, Message: entry.Message, Level: entry.Level.String(), }) if err != nil { return Wrap(err) } conn, err := net.ListenPacket("udp", ":0") if err != nil { return Wrap(err) } defer conn.Close() resolvedAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:5000") if err != nil { return Wrap(err) } _, err = (conn.(*net.UDPConn)).WriteToUDP(data, resolvedAddr) return Wrap(err) }
[ "func", "(", "elk", "*", "UDPHook", ")", "Fire", "(", "e", "*", "log", ".", "Entry", ")", "error", "{", "// Make a copy to safely modify", "entry", ":=", "e", ".", "WithFields", "(", "nil", ")", "\n", "if", "cursor", ":=", "findFrame", "(", ")", ";", "cursor", "!=", "nil", "{", "t", ":=", "newTraceFromFrames", "(", "*", "cursor", ",", "nil", ")", "\n", "entry", ".", "Data", "[", "FileField", "]", "=", "t", ".", "String", "(", ")", "\n", "entry", ".", "Data", "[", "FunctionField", "]", "=", "t", ".", "Func", "(", ")", "\n", "}", "\n", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "Frame", "{", "Time", ":", "elk", ".", "Clock", ".", "Now", "(", ")", ".", "UTC", "(", ")", ",", "Type", ":", "\"", "\"", ",", "Entry", ":", "entry", ".", "Data", ",", "Message", ":", "entry", ".", "Message", ",", "Level", ":", "entry", ".", "Level", ".", "String", "(", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "conn", ",", "err", ":=", "net", ".", "ListenPacket", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "resolvedAddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "(", "conn", ".", "(", "*", "net", ".", "UDPConn", ")", ")", ".", "WriteToUDP", "(", "data", ",", "resolvedAddr", ")", "\n", "return", "Wrap", "(", "err", ")", "\n\n", "}" ]
// Fire fires the event to the ELK beat
[ "Fire", "fires", "the", "event", "to", "the", "ELK", "beat" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/udphook.go#L67-L100
10,623
gravitational/trace
udphook.go
Levels
func (elk *UDPHook) Levels() []log.Level { return []log.Level{ log.PanicLevel, log.FatalLevel, log.ErrorLevel, log.WarnLevel, log.InfoLevel, log.DebugLevel, } }
go
func (elk *UDPHook) Levels() []log.Level { return []log.Level{ log.PanicLevel, log.FatalLevel, log.ErrorLevel, log.WarnLevel, log.InfoLevel, log.DebugLevel, } }
[ "func", "(", "elk", "*", "UDPHook", ")", "Levels", "(", ")", "[", "]", "log", ".", "Level", "{", "return", "[", "]", "log", ".", "Level", "{", "log", ".", "PanicLevel", ",", "log", ".", "FatalLevel", ",", "log", ".", "ErrorLevel", ",", "log", ".", "WarnLevel", ",", "log", ".", "InfoLevel", ",", "log", ".", "DebugLevel", ",", "}", "\n", "}" ]
// Levels returns logging levels supported by logrus
[ "Levels", "returns", "logging", "levels", "supported", "by", "logrus" ]
f30095ced5ff011085d26f160468dcc477607730
https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/udphook.go#L103-L112
10,624
wvanbergen/kazoo-go
topic_admin.go
CreateTopic
func (kz *Kazoo) CreateTopic(name string, partitionCount int, replicationFactor int, topicConfig map[string]string) error { topic := kz.Topic(name) // Official kafka sdk checks if topic exists, then always writes the config unconditionally // but only writes the partition map if ones does not exist. exists, err := topic.Exists() if err != nil { return err } else if exists { return ErrTopicExists } brokerList, err := kz.brokerIDList() if err != nil { return err } partitionList, err := topic.generatePartitionAssignments(brokerList, partitionCount, replicationFactor) if err != nil { return err } configData, err := topic.marshalConfig(topicConfig) if err != nil { return err } partitionData, err := topic.marshalPartitions(partitionList) if err != nil { return err } if err = kz.createOrUpdate(topic.configPath(), configData, false); err != nil { return err } if err = kz.create(topic.metadataPath(), partitionData, false); err != nil { return err } return nil }
go
func (kz *Kazoo) CreateTopic(name string, partitionCount int, replicationFactor int, topicConfig map[string]string) error { topic := kz.Topic(name) // Official kafka sdk checks if topic exists, then always writes the config unconditionally // but only writes the partition map if ones does not exist. exists, err := topic.Exists() if err != nil { return err } else if exists { return ErrTopicExists } brokerList, err := kz.brokerIDList() if err != nil { return err } partitionList, err := topic.generatePartitionAssignments(brokerList, partitionCount, replicationFactor) if err != nil { return err } configData, err := topic.marshalConfig(topicConfig) if err != nil { return err } partitionData, err := topic.marshalPartitions(partitionList) if err != nil { return err } if err = kz.createOrUpdate(topic.configPath(), configData, false); err != nil { return err } if err = kz.create(topic.metadataPath(), partitionData, false); err != nil { return err } return nil }
[ "func", "(", "kz", "*", "Kazoo", ")", "CreateTopic", "(", "name", "string", ",", "partitionCount", "int", ",", "replicationFactor", "int", ",", "topicConfig", "map", "[", "string", "]", "string", ")", "error", "{", "topic", ":=", "kz", ".", "Topic", "(", "name", ")", "\n\n", "// Official kafka sdk checks if topic exists, then always writes the config unconditionally", "// but only writes the partition map if ones does not exist.", "exists", ",", "err", ":=", "topic", ".", "Exists", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "exists", "{", "return", "ErrTopicExists", "\n", "}", "\n\n", "brokerList", ",", "err", ":=", "kz", ".", "brokerIDList", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "partitionList", ",", "err", ":=", "topic", ".", "generatePartitionAssignments", "(", "brokerList", ",", "partitionCount", ",", "replicationFactor", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "configData", ",", "err", ":=", "topic", ".", "marshalConfig", "(", "topicConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "partitionData", ",", "err", ":=", "topic", ".", "marshalPartitions", "(", "partitionList", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", "=", "kz", ".", "createOrUpdate", "(", "topic", ".", "configPath", "(", ")", ",", "configData", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", "=", "kz", ".", "create", "(", "topic", ".", "metadataPath", "(", ")", ",", "partitionData", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CreateTopic creates a new kafka topic with the specified parameters and properties
[ "CreateTopic", "creates", "a", "new", "kafka", "topic", "with", "the", "specified", "parameters", "and", "properties" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_admin.go#L18-L59
10,625
wvanbergen/kazoo-go
topic_admin.go
DeleteTopic
func (kz *Kazoo) DeleteTopic(name string) error { node := fmt.Sprintf("%s/admin/delete_topics/%s", kz.conf.Chroot, name) exists, err := kz.exists(node) if err != nil { return err } if exists { return ErrTopicMarkedForDelete } if err := kz.create(node, nil, false); err != nil { return err } return nil }
go
func (kz *Kazoo) DeleteTopic(name string) error { node := fmt.Sprintf("%s/admin/delete_topics/%s", kz.conf.Chroot, name) exists, err := kz.exists(node) if err != nil { return err } if exists { return ErrTopicMarkedForDelete } if err := kz.create(node, nil, false); err != nil { return err } return nil }
[ "func", "(", "kz", "*", "Kazoo", ")", "DeleteTopic", "(", "name", "string", ")", "error", "{", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "kz", ".", "conf", ".", "Chroot", ",", "name", ")", "\n\n", "exists", ",", "err", ":=", "kz", ".", "exists", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "exists", "{", "return", "ErrTopicMarkedForDelete", "\n", "}", "\n\n", "if", "err", ":=", "kz", ".", "create", "(", "node", ",", "nil", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteTopic marks a kafka topic for deletion. Deleting a topic is asynchronous and // DeleteTopic will return before Kafka actually does the deletion.
[ "DeleteTopic", "marks", "a", "kafka", "topic", "for", "deletion", ".", "Deleting", "a", "topic", "is", "asynchronous", "and", "DeleteTopic", "will", "return", "before", "Kafka", "actually", "does", "the", "deletion", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_admin.go#L63-L78
10,626
wvanbergen/kazoo-go
topic_admin.go
DeleteTopicSync
func (kz *Kazoo) DeleteTopicSync(name string, timeout time.Duration) error { err := kz.DeleteTopic(name) if err != nil { return err } topic := kz.Topic(name) if exists, err := topic.Exists(); err != nil { return err } else if !exists { return nil } changes, err := topic.Watch() if err != nil { return nil } if timeout > 0 { timer := time.NewTimer(timeout) defer timer.Stop() for { select { case <-timer.C: return ErrDeletionTimedOut case c := <-changes: if c.Type == zk.EventNodeDeleted { return nil } } } } else { for { select { case c := <-changes: if c.Type == zk.EventNodeDeleted { return nil } } } } }
go
func (kz *Kazoo) DeleteTopicSync(name string, timeout time.Duration) error { err := kz.DeleteTopic(name) if err != nil { return err } topic := kz.Topic(name) if exists, err := topic.Exists(); err != nil { return err } else if !exists { return nil } changes, err := topic.Watch() if err != nil { return nil } if timeout > 0 { timer := time.NewTimer(timeout) defer timer.Stop() for { select { case <-timer.C: return ErrDeletionTimedOut case c := <-changes: if c.Type == zk.EventNodeDeleted { return nil } } } } else { for { select { case c := <-changes: if c.Type == zk.EventNodeDeleted { return nil } } } } }
[ "func", "(", "kz", "*", "Kazoo", ")", "DeleteTopicSync", "(", "name", "string", ",", "timeout", "time", ".", "Duration", ")", "error", "{", "err", ":=", "kz", ".", "DeleteTopic", "(", "name", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "topic", ":=", "kz", ".", "Topic", "(", "name", ")", "\n\n", "if", "exists", ",", "err", ":=", "topic", ".", "Exists", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "!", "exists", "{", "return", "nil", "\n", "}", "\n\n", "changes", ",", "err", ":=", "topic", ".", "Watch", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "timeout", ">", "0", "{", "timer", ":=", "time", ".", "NewTimer", "(", "timeout", ")", "\n", "defer", "timer", ".", "Stop", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "timer", ".", "C", ":", "return", "ErrDeletionTimedOut", "\n\n", "case", "c", ":=", "<-", "changes", ":", "if", "c", ".", "Type", "==", "zk", ".", "EventNodeDeleted", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "}", "else", "{", "for", "{", "select", "{", "case", "c", ":=", "<-", "changes", ":", "if", "c", ".", "Type", "==", "zk", ".", "EventNodeDeleted", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// DeleteTopicSync marks a kafka topic for deletion and waits until it is deleted // before returning.
[ "DeleteTopicSync", "marks", "a", "kafka", "topic", "for", "deletion", "and", "waits", "until", "it", "is", "deleted", "before", "returning", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_admin.go#L82-L130
10,627
wvanbergen/kazoo-go
kazoo.go
NewKazoo
func NewKazoo(servers []string, conf *Config) (*Kazoo, error) { if conf == nil { conf = NewConfig() } conn, _, err := zk.Connect( servers, conf.Timeout, func(c *zk.Conn) { c.SetLogger(conf.Logger) }, ) if err != nil { return nil, err } return &Kazoo{conn, conf}, nil }
go
func NewKazoo(servers []string, conf *Config) (*Kazoo, error) { if conf == nil { conf = NewConfig() } conn, _, err := zk.Connect( servers, conf.Timeout, func(c *zk.Conn) { c.SetLogger(conf.Logger) }, ) if err != nil { return nil, err } return &Kazoo{conn, conf}, nil }
[ "func", "NewKazoo", "(", "servers", "[", "]", "string", ",", "conf", "*", "Config", ")", "(", "*", "Kazoo", ",", "error", ")", "{", "if", "conf", "==", "nil", "{", "conf", "=", "NewConfig", "(", ")", "\n", "}", "\n\n", "conn", ",", "_", ",", "err", ":=", "zk", ".", "Connect", "(", "servers", ",", "conf", ".", "Timeout", ",", "func", "(", "c", "*", "zk", ".", "Conn", ")", "{", "c", ".", "SetLogger", "(", "conf", ".", "Logger", ")", "}", ",", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Kazoo", "{", "conn", ",", "conf", "}", ",", "nil", "\n", "}" ]
// NewKazoo creates a new connection instance
[ "NewKazoo", "creates", "a", "new", "connection", "instance" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/kazoo.go#L72-L87
10,628
wvanbergen/kazoo-go
kazoo.go
NewKazooFromConnectionString
func NewKazooFromConnectionString(connectionString string, conf *Config) (*Kazoo, error) { if conf == nil { conf = NewConfig() } nodes, chroot := ParseConnectionString(connectionString) conf.Chroot = chroot return NewKazoo(nodes, conf) }
go
func NewKazooFromConnectionString(connectionString string, conf *Config) (*Kazoo, error) { if conf == nil { conf = NewConfig() } nodes, chroot := ParseConnectionString(connectionString) conf.Chroot = chroot return NewKazoo(nodes, conf) }
[ "func", "NewKazooFromConnectionString", "(", "connectionString", "string", ",", "conf", "*", "Config", ")", "(", "*", "Kazoo", ",", "error", ")", "{", "if", "conf", "==", "nil", "{", "conf", "=", "NewConfig", "(", ")", "\n", "}", "\n\n", "nodes", ",", "chroot", ":=", "ParseConnectionString", "(", "connectionString", ")", "\n", "conf", ".", "Chroot", "=", "chroot", "\n", "return", "NewKazoo", "(", "nodes", ",", "conf", ")", "\n", "}" ]
// NewKazooFromConnectionString creates a new connection instance // based on a zookeeer connection string that can include a chroot.
[ "NewKazooFromConnectionString", "creates", "a", "new", "connection", "instance", "based", "on", "a", "zookeeer", "connection", "string", "that", "can", "include", "a", "chroot", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/kazoo.go#L91-L99
10,629
wvanbergen/kazoo-go
kazoo.go
Brokers
func (kz *Kazoo) Brokers() (map[int32]string, error) { root := fmt.Sprintf("%s/brokers/ids", kz.conf.Chroot) children, _, err := kz.conn.Children(root) if err != nil { return nil, err } type brokerEntry struct { Host string `json:"host"` Port int `json:"port"` } result := make(map[int32]string) for _, child := range children { brokerID, err := strconv.ParseInt(child, 10, 32) if err != nil { return nil, err } value, _, err := kz.conn.Get(path.Join(root, child)) if err != nil { return nil, err } var brokerNode brokerEntry if err := json.Unmarshal(value, &brokerNode); err != nil { return nil, err } result[int32(brokerID)] = fmt.Sprintf("%s:%d", brokerNode.Host, brokerNode.Port) } return result, nil }
go
func (kz *Kazoo) Brokers() (map[int32]string, error) { root := fmt.Sprintf("%s/brokers/ids", kz.conf.Chroot) children, _, err := kz.conn.Children(root) if err != nil { return nil, err } type brokerEntry struct { Host string `json:"host"` Port int `json:"port"` } result := make(map[int32]string) for _, child := range children { brokerID, err := strconv.ParseInt(child, 10, 32) if err != nil { return nil, err } value, _, err := kz.conn.Get(path.Join(root, child)) if err != nil { return nil, err } var brokerNode brokerEntry if err := json.Unmarshal(value, &brokerNode); err != nil { return nil, err } result[int32(brokerID)] = fmt.Sprintf("%s:%d", brokerNode.Host, brokerNode.Port) } return result, nil }
[ "func", "(", "kz", "*", "Kazoo", ")", "Brokers", "(", ")", "(", "map", "[", "int32", "]", "string", ",", "error", ")", "{", "root", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "kz", ".", "conf", ".", "Chroot", ")", "\n", "children", ",", "_", ",", "err", ":=", "kz", ".", "conn", ".", "Children", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "type", "brokerEntry", "struct", "{", "Host", "string", "`json:\"host\"`", "\n", "Port", "int", "`json:\"port\"`", "\n", "}", "\n\n", "result", ":=", "make", "(", "map", "[", "int32", "]", "string", ")", "\n", "for", "_", ",", "child", ":=", "range", "children", "{", "brokerID", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "child", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "value", ",", "_", ",", "err", ":=", "kz", ".", "conn", ".", "Get", "(", "path", ".", "Join", "(", "root", ",", "child", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "brokerNode", "brokerEntry", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "value", ",", "&", "brokerNode", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "result", "[", "int32", "(", "brokerID", ")", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "brokerNode", ".", "Host", ",", "brokerNode", ".", "Port", ")", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// Brokers returns a map of all the brokers that make part of the // Kafka cluster that is registered in Zookeeper.
[ "Brokers", "returns", "a", "map", "of", "all", "the", "brokers", "that", "make", "part", "of", "the", "Kafka", "cluster", "that", "is", "registered", "in", "Zookeeper", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/kazoo.go#L103-L136
10,630
wvanbergen/kazoo-go
kazoo.go
brokerIDList
func (kz *Kazoo) brokerIDList() ([]int32, error) { brokers, err := kz.Brokers() if err != nil { return nil, err } result := make([]int32, 0, len(brokers)) for id := range brokers { result = append(result, id) } // return sorted list to match the offical kafka sdks sort.Sort(int32Slice(result)) return result, nil }
go
func (kz *Kazoo) brokerIDList() ([]int32, error) { brokers, err := kz.Brokers() if err != nil { return nil, err } result := make([]int32, 0, len(brokers)) for id := range brokers { result = append(result, id) } // return sorted list to match the offical kafka sdks sort.Sort(int32Slice(result)) return result, nil }
[ "func", "(", "kz", "*", "Kazoo", ")", "brokerIDList", "(", ")", "(", "[", "]", "int32", ",", "error", ")", "{", "brokers", ",", "err", ":=", "kz", ".", "Brokers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "result", ":=", "make", "(", "[", "]", "int32", ",", "0", ",", "len", "(", "brokers", ")", ")", "\n", "for", "id", ":=", "range", "brokers", "{", "result", "=", "append", "(", "result", ",", "id", ")", "\n", "}", "\n\n", "// return sorted list to match the offical kafka sdks", "sort", ".", "Sort", "(", "int32Slice", "(", "result", ")", ")", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// BrokerIDList returns a sorted slice of broker ids that can be used for manipulating topics and partitions.`.
[ "BrokerIDList", "returns", "a", "sorted", "slice", "of", "broker", "ids", "that", "can", "be", "used", "for", "manipulating", "topics", "and", "partitions", ".", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/kazoo.go#L155-L170
10,631
wvanbergen/kazoo-go
kazoo.go
Controller
func (kz *Kazoo) Controller() (int32, error) { type controllerEntry struct { BrokerID int32 `json:"brokerid"` } node := fmt.Sprintf("%s/controller", kz.conf.Chroot) data, _, err := kz.conn.Get(node) if err != nil { return -1, err } var controllerNode controllerEntry if err := json.Unmarshal(data, &controllerNode); err != nil { return -1, err } return controllerNode.BrokerID, nil }
go
func (kz *Kazoo) Controller() (int32, error) { type controllerEntry struct { BrokerID int32 `json:"brokerid"` } node := fmt.Sprintf("%s/controller", kz.conf.Chroot) data, _, err := kz.conn.Get(node) if err != nil { return -1, err } var controllerNode controllerEntry if err := json.Unmarshal(data, &controllerNode); err != nil { return -1, err } return controllerNode.BrokerID, nil }
[ "func", "(", "kz", "*", "Kazoo", ")", "Controller", "(", ")", "(", "int32", ",", "error", ")", "{", "type", "controllerEntry", "struct", "{", "BrokerID", "int32", "`json:\"brokerid\"`", "\n", "}", "\n\n", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "kz", ".", "conf", ".", "Chroot", ")", "\n", "data", ",", "_", ",", "err", ":=", "kz", ".", "conn", ".", "Get", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n\n", "var", "controllerNode", "controllerEntry", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "controllerNode", ")", ";", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n\n", "return", "controllerNode", ".", "BrokerID", ",", "nil", "\n", "}" ]
// Controller returns what broker is currently acting as controller of the Kafka cluster
[ "Controller", "returns", "what", "broker", "is", "currently", "acting", "as", "controller", "of", "the", "Kafka", "cluster" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/kazoo.go#L173-L190
10,632
wvanbergen/kazoo-go
kazoo.go
deleteRecursive
func (kz *Kazoo) deleteRecursive(node string) (err error) { children, stat, err := kz.conn.Children(node) if err == zk.ErrNoNode { return nil } else if err != nil { return } for _, child := range children { if err = kz.deleteRecursive(path.Join(node, child)); err != nil { return } } return kz.conn.Delete(node, stat.Version) }
go
func (kz *Kazoo) deleteRecursive(node string) (err error) { children, stat, err := kz.conn.Children(node) if err == zk.ErrNoNode { return nil } else if err != nil { return } for _, child := range children { if err = kz.deleteRecursive(path.Join(node, child)); err != nil { return } } return kz.conn.Delete(node, stat.Version) }
[ "func", "(", "kz", "*", "Kazoo", ")", "deleteRecursive", "(", "node", "string", ")", "(", "err", "error", ")", "{", "children", ",", "stat", ",", "err", ":=", "kz", ".", "conn", ".", "Children", "(", "node", ")", "\n", "if", "err", "==", "zk", ".", "ErrNoNode", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "for", "_", ",", "child", ":=", "range", "children", "{", "if", "err", "=", "kz", ".", "deleteRecursive", "(", "path", ".", "Join", "(", "node", ",", "child", ")", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "return", "kz", ".", "conn", ".", "Delete", "(", "node", ",", "stat", ".", "Version", ")", "\n", "}" ]
// DeleteAll deletes a node recursively
[ "DeleteAll", "deletes", "a", "node", "recursively" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/kazoo.go#L209-L224
10,633
wvanbergen/kazoo-go
kazoo.go
mkdirRecursive
func (kz *Kazoo) mkdirRecursive(node string) (err error) { parent := path.Dir(node) if parent != "/" { if err = kz.mkdirRecursive(parent); err != nil { return } } exists, _, err := kz.conn.Exists(node) if err != nil { return } if !exists { _, err = kz.conn.Create(node, nil, 0, zk.WorldACL(zk.PermAll)) return } return }
go
func (kz *Kazoo) mkdirRecursive(node string) (err error) { parent := path.Dir(node) if parent != "/" { if err = kz.mkdirRecursive(parent); err != nil { return } } exists, _, err := kz.conn.Exists(node) if err != nil { return } if !exists { _, err = kz.conn.Create(node, nil, 0, zk.WorldACL(zk.PermAll)) return } return }
[ "func", "(", "kz", "*", "Kazoo", ")", "mkdirRecursive", "(", "node", "string", ")", "(", "err", "error", ")", "{", "parent", ":=", "path", ".", "Dir", "(", "node", ")", "\n", "if", "parent", "!=", "\"", "\"", "{", "if", "err", "=", "kz", ".", "mkdirRecursive", "(", "parent", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "exists", ",", "_", ",", "err", ":=", "kz", ".", "conn", ".", "Exists", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "!", "exists", "{", "_", ",", "err", "=", "kz", ".", "conn", ".", "Create", "(", "node", ",", "nil", ",", "0", ",", "zk", ".", "WorldACL", "(", "zk", ".", "PermAll", ")", ")", "\n", "return", "\n", "}", "\n\n", "return", "\n", "}" ]
// MkdirAll creates a directory recursively
[ "MkdirAll", "creates", "a", "directory", "recursively" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/kazoo.go#L227-L246
10,634
wvanbergen/kazoo-go
kazoo.go
create
func (kz *Kazoo) create(node string, value []byte, ephemeral bool) (err error) { if err = kz.mkdirRecursive(path.Dir(node)); err != nil { return } flags := int32(0) if ephemeral { flags = zk.FlagEphemeral } _, err = kz.conn.Create(node, value, flags, zk.WorldACL(zk.PermAll)) return }
go
func (kz *Kazoo) create(node string, value []byte, ephemeral bool) (err error) { if err = kz.mkdirRecursive(path.Dir(node)); err != nil { return } flags := int32(0) if ephemeral { flags = zk.FlagEphemeral } _, err = kz.conn.Create(node, value, flags, zk.WorldACL(zk.PermAll)) return }
[ "func", "(", "kz", "*", "Kazoo", ")", "create", "(", "node", "string", ",", "value", "[", "]", "byte", ",", "ephemeral", "bool", ")", "(", "err", "error", ")", "{", "if", "err", "=", "kz", ".", "mkdirRecursive", "(", "path", ".", "Dir", "(", "node", ")", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "flags", ":=", "int32", "(", "0", ")", "\n", "if", "ephemeral", "{", "flags", "=", "zk", ".", "FlagEphemeral", "\n", "}", "\n", "_", ",", "err", "=", "kz", ".", "conn", ".", "Create", "(", "node", ",", "value", ",", "flags", ",", "zk", ".", "WorldACL", "(", "zk", ".", "PermAll", ")", ")", "\n", "return", "\n", "}" ]
// Create stores a new value at node. Fails if already set.
[ "Create", "stores", "a", "new", "value", "at", "node", ".", "Fails", "if", "already", "set", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/kazoo.go#L249-L260
10,635
wvanbergen/kazoo-go
kazoo.go
createOrUpdate
func (kz *Kazoo) createOrUpdate(node string, value []byte, ephemeral bool) (err error) { if _, err = kz.conn.Set(node, value, -1); err == nil { return } if err == zk.ErrNoNode { err = kz.create(node, value, ephemeral) } return }
go
func (kz *Kazoo) createOrUpdate(node string, value []byte, ephemeral bool) (err error) { if _, err = kz.conn.Set(node, value, -1); err == nil { return } if err == zk.ErrNoNode { err = kz.create(node, value, ephemeral) } return }
[ "func", "(", "kz", "*", "Kazoo", ")", "createOrUpdate", "(", "node", "string", ",", "value", "[", "]", "byte", ",", "ephemeral", "bool", ")", "(", "err", "error", ")", "{", "if", "_", ",", "err", "=", "kz", ".", "conn", ".", "Set", "(", "node", ",", "value", ",", "-", "1", ")", ";", "err", "==", "nil", "{", "return", "\n", "}", "\n\n", "if", "err", "==", "zk", ".", "ErrNoNode", "{", "err", "=", "kz", ".", "create", "(", "node", ",", "value", ",", "ephemeral", ")", "\n", "}", "\n", "return", "\n", "}" ]
// createOrUpdate first attempts to update a node. If the nodes does not exist it will create it.
[ "createOrUpdate", "first", "attempts", "to", "update", "a", "node", ".", "If", "the", "nodes", "does", "not", "exist", "it", "will", "create", "it", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/kazoo.go#L263-L272
10,636
wvanbergen/kazoo-go
consumergroup.go
Consumergroups
func (kz *Kazoo) Consumergroups() (ConsumergroupList, error) { root := fmt.Sprintf("%s/consumers", kz.conf.Chroot) cgs, _, err := kz.conn.Children(root) if err != nil { return nil, err } result := make(ConsumergroupList, 0, len(cgs)) for _, cg := range cgs { result = append(result, kz.Consumergroup(cg)) } return result, nil }
go
func (kz *Kazoo) Consumergroups() (ConsumergroupList, error) { root := fmt.Sprintf("%s/consumers", kz.conf.Chroot) cgs, _, err := kz.conn.Children(root) if err != nil { return nil, err } result := make(ConsumergroupList, 0, len(cgs)) for _, cg := range cgs { result = append(result, kz.Consumergroup(cg)) } return result, nil }
[ "func", "(", "kz", "*", "Kazoo", ")", "Consumergroups", "(", ")", "(", "ConsumergroupList", ",", "error", ")", "{", "root", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "kz", ".", "conf", ".", "Chroot", ")", "\n", "cgs", ",", "_", ",", "err", ":=", "kz", ".", "conn", ".", "Children", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "result", ":=", "make", "(", "ConsumergroupList", ",", "0", ",", "len", "(", "cgs", ")", ")", "\n", "for", "_", ",", "cg", ":=", "range", "cgs", "{", "result", "=", "append", "(", "result", ",", "kz", ".", "Consumergroup", "(", "cg", ")", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Consumergroups returns all the registered consumergroups
[ "Consumergroups", "returns", "all", "the", "registered", "consumergroups" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L64-L76
10,637
wvanbergen/kazoo-go
consumergroup.go
Consumergroup
func (kz *Kazoo) Consumergroup(name string) *Consumergroup { return &Consumergroup{Name: name, kz: kz} }
go
func (kz *Kazoo) Consumergroup(name string) *Consumergroup { return &Consumergroup{Name: name, kz: kz} }
[ "func", "(", "kz", "*", "Kazoo", ")", "Consumergroup", "(", "name", "string", ")", "*", "Consumergroup", "{", "return", "&", "Consumergroup", "{", "Name", ":", "name", ",", "kz", ":", "kz", "}", "\n", "}" ]
// Consumergroup instantiates a new consumergroup.
[ "Consumergroup", "instantiates", "a", "new", "consumergroup", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L79-L81
10,638
wvanbergen/kazoo-go
consumergroup.go
Exists
func (cg *Consumergroup) Exists() (bool, error) { return cg.kz.exists(fmt.Sprintf("%s/consumers/%s", cg.kz.conf.Chroot, cg.Name)) }
go
func (cg *Consumergroup) Exists() (bool, error) { return cg.kz.exists(fmt.Sprintf("%s/consumers/%s", cg.kz.conf.Chroot, cg.Name)) }
[ "func", "(", "cg", "*", "Consumergroup", ")", "Exists", "(", ")", "(", "bool", ",", "error", ")", "{", "return", "cg", ".", "kz", ".", "exists", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cg", ".", "Name", ")", ")", "\n", "}" ]
// Exists checks whether the consumergroup has been registered in Zookeeper
[ "Exists", "checks", "whether", "the", "consumergroup", "has", "been", "registered", "in", "Zookeeper" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L84-L86
10,639
wvanbergen/kazoo-go
consumergroup.go
Create
func (cg *Consumergroup) Create() error { return cg.kz.mkdirRecursive(fmt.Sprintf("%s/consumers/%s", cg.kz.conf.Chroot, cg.Name)) }
go
func (cg *Consumergroup) Create() error { return cg.kz.mkdirRecursive(fmt.Sprintf("%s/consumers/%s", cg.kz.conf.Chroot, cg.Name)) }
[ "func", "(", "cg", "*", "Consumergroup", ")", "Create", "(", ")", "error", "{", "return", "cg", ".", "kz", ".", "mkdirRecursive", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cg", ".", "Name", ")", ")", "\n", "}" ]
// Create registers the consumergroup in zookeeper
[ "Create", "registers", "the", "consumergroup", "in", "zookeeper" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L89-L91
10,640
wvanbergen/kazoo-go
consumergroup.go
Delete
func (cg *Consumergroup) Delete() error { if instances, err := cg.Instances(); err != nil { return err } else if len(instances) > 0 { return ErrRunningInstances } return cg.kz.deleteRecursive(fmt.Sprintf("%s/consumers/%s", cg.kz.conf.Chroot, cg.Name)) }
go
func (cg *Consumergroup) Delete() error { if instances, err := cg.Instances(); err != nil { return err } else if len(instances) > 0 { return ErrRunningInstances } return cg.kz.deleteRecursive(fmt.Sprintf("%s/consumers/%s", cg.kz.conf.Chroot, cg.Name)) }
[ "func", "(", "cg", "*", "Consumergroup", ")", "Delete", "(", ")", "error", "{", "if", "instances", ",", "err", ":=", "cg", ".", "Instances", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "len", "(", "instances", ")", ">", "0", "{", "return", "ErrRunningInstances", "\n", "}", "\n\n", "return", "cg", ".", "kz", ".", "deleteRecursive", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cg", ".", "Name", ")", ")", "\n", "}" ]
// Delete removes the consumergroup from zookeeper
[ "Delete", "removes", "the", "consumergroup", "from", "zookeeper" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L94-L102
10,641
wvanbergen/kazoo-go
consumergroup.go
Instances
func (cg *Consumergroup) Instances() (ConsumergroupInstanceList, error) { root := fmt.Sprintf("%s/consumers/%s/ids", cg.kz.conf.Chroot, cg.Name) cgis, _, err := cg.kz.conn.Children(root) if err != nil { if err == zk.ErrNoNode { result := make(ConsumergroupInstanceList, 0) return result, nil } return nil, err } result := make(ConsumergroupInstanceList, 0, len(cgis)) for _, cgi := range cgis { result = append(result, cg.Instance(cgi)) } return result, nil }
go
func (cg *Consumergroup) Instances() (ConsumergroupInstanceList, error) { root := fmt.Sprintf("%s/consumers/%s/ids", cg.kz.conf.Chroot, cg.Name) cgis, _, err := cg.kz.conn.Children(root) if err != nil { if err == zk.ErrNoNode { result := make(ConsumergroupInstanceList, 0) return result, nil } return nil, err } result := make(ConsumergroupInstanceList, 0, len(cgis)) for _, cgi := range cgis { result = append(result, cg.Instance(cgi)) } return result, nil }
[ "func", "(", "cg", "*", "Consumergroup", ")", "Instances", "(", ")", "(", "ConsumergroupInstanceList", ",", "error", ")", "{", "root", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cg", ".", "Name", ")", "\n", "cgis", ",", "_", ",", "err", ":=", "cg", ".", "kz", ".", "conn", ".", "Children", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "zk", ".", "ErrNoNode", "{", "result", ":=", "make", "(", "ConsumergroupInstanceList", ",", "0", ")", "\n", "return", "result", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "result", ":=", "make", "(", "ConsumergroupInstanceList", ",", "0", ",", "len", "(", "cgis", ")", ")", "\n", "for", "_", ",", "cgi", ":=", "range", "cgis", "{", "result", "=", "append", "(", "result", ",", "cg", ".", "Instance", "(", "cgi", ")", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Instances returns a map of all running instances inside this consumergroup.
[ "Instances", "returns", "a", "map", "of", "all", "running", "instances", "inside", "this", "consumergroup", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L105-L121
10,642
wvanbergen/kazoo-go
consumergroup.go
WatchInstances
func (cg *Consumergroup) WatchInstances() (ConsumergroupInstanceList, <-chan zk.Event, error) { node := fmt.Sprintf("%s/consumers/%s/ids", cg.kz.conf.Chroot, cg.Name) cgis, _, c, err := cg.kz.conn.ChildrenW(node) if err != nil { if err != zk.ErrNoNode { return nil, nil, err } if err := cg.kz.mkdirRecursive(node); err != nil { return nil, nil, err } if cgis, _, c, err = cg.kz.conn.ChildrenW(node); err != nil { return nil, nil, err } } result := make(ConsumergroupInstanceList, 0, len(cgis)) for _, cgi := range cgis { result = append(result, cg.Instance(cgi)) } return result, c, nil }
go
func (cg *Consumergroup) WatchInstances() (ConsumergroupInstanceList, <-chan zk.Event, error) { node := fmt.Sprintf("%s/consumers/%s/ids", cg.kz.conf.Chroot, cg.Name) cgis, _, c, err := cg.kz.conn.ChildrenW(node) if err != nil { if err != zk.ErrNoNode { return nil, nil, err } if err := cg.kz.mkdirRecursive(node); err != nil { return nil, nil, err } if cgis, _, c, err = cg.kz.conn.ChildrenW(node); err != nil { return nil, nil, err } } result := make(ConsumergroupInstanceList, 0, len(cgis)) for _, cgi := range cgis { result = append(result, cg.Instance(cgi)) } return result, c, nil }
[ "func", "(", "cg", "*", "Consumergroup", ")", "WatchInstances", "(", ")", "(", "ConsumergroupInstanceList", ",", "<-", "chan", "zk", ".", "Event", ",", "error", ")", "{", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cg", ".", "Name", ")", "\n", "cgis", ",", "_", ",", "c", ",", "err", ":=", "cg", ".", "kz", ".", "conn", ".", "ChildrenW", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "zk", ".", "ErrNoNode", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "cg", ".", "kz", ".", "mkdirRecursive", "(", "node", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "if", "cgis", ",", "_", ",", "c", ",", "err", "=", "cg", ".", "kz", ".", "conn", ".", "ChildrenW", "(", "node", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "result", ":=", "make", "(", "ConsumergroupInstanceList", ",", "0", ",", "len", "(", "cgis", ")", ")", "\n", "for", "_", ",", "cgi", ":=", "range", "cgis", "{", "result", "=", "append", "(", "result", ",", "cg", ".", "Instance", "(", "cgi", ")", ")", "\n", "}", "\n\n", "return", "result", ",", "c", ",", "nil", "\n", "}" ]
// WatchInstances returns a ConsumergroupInstanceList, and a channel that will be closed // as soon the instance list changes.
[ "WatchInstances", "returns", "a", "ConsumergroupInstanceList", "and", "a", "channel", "that", "will", "be", "closed", "as", "soon", "the", "instance", "list", "changes", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L125-L146
10,643
wvanbergen/kazoo-go
consumergroup.go
NewInstance
func (cg *Consumergroup) NewInstance() *ConsumergroupInstance { id, err := generateConsumerInstanceID() if err != nil { panic(err) } return cg.Instance(id) }
go
func (cg *Consumergroup) NewInstance() *ConsumergroupInstance { id, err := generateConsumerInstanceID() if err != nil { panic(err) } return cg.Instance(id) }
[ "func", "(", "cg", "*", "Consumergroup", ")", "NewInstance", "(", ")", "*", "ConsumergroupInstance", "{", "id", ",", "err", ":=", "generateConsumerInstanceID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "cg", ".", "Instance", "(", "id", ")", "\n", "}" ]
// NewInstance instantiates a new ConsumergroupInstance inside this consumer group, // using a newly generated ID.
[ "NewInstance", "instantiates", "a", "new", "ConsumergroupInstance", "inside", "this", "consumer", "group", "using", "a", "newly", "generated", "ID", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L150-L156
10,644
wvanbergen/kazoo-go
consumergroup.go
Instance
func (cg *Consumergroup) Instance(id string) *ConsumergroupInstance { return &ConsumergroupInstance{cg: cg, ID: id} }
go
func (cg *Consumergroup) Instance(id string) *ConsumergroupInstance { return &ConsumergroupInstance{cg: cg, ID: id} }
[ "func", "(", "cg", "*", "Consumergroup", ")", "Instance", "(", "id", "string", ")", "*", "ConsumergroupInstance", "{", "return", "&", "ConsumergroupInstance", "{", "cg", ":", "cg", ",", "ID", ":", "id", "}", "\n", "}" ]
// Instance instantiates a new ConsumergroupInstance inside this consumer group, // using an existing ID.
[ "Instance", "instantiates", "a", "new", "ConsumergroupInstance", "inside", "this", "consumer", "group", "using", "an", "existing", "ID", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L160-L162
10,645
wvanbergen/kazoo-go
consumergroup.go
PartitionOwner
func (cg *Consumergroup) PartitionOwner(topic string, partition int32) (*ConsumergroupInstance, error) { node := fmt.Sprintf("%s/consumers/%s/owners/%s/%d", cg.kz.conf.Chroot, cg.Name, topic, partition) val, _, err := cg.kz.conn.Get(node) // If the node does not exists, nobody has claimed it. switch err { case nil: return &ConsumergroupInstance{cg: cg, ID: string(val)}, nil case zk.ErrNoNode: return nil, nil default: return nil, err } }
go
func (cg *Consumergroup) PartitionOwner(topic string, partition int32) (*ConsumergroupInstance, error) { node := fmt.Sprintf("%s/consumers/%s/owners/%s/%d", cg.kz.conf.Chroot, cg.Name, topic, partition) val, _, err := cg.kz.conn.Get(node) // If the node does not exists, nobody has claimed it. switch err { case nil: return &ConsumergroupInstance{cg: cg, ID: string(val)}, nil case zk.ErrNoNode: return nil, nil default: return nil, err } }
[ "func", "(", "cg", "*", "Consumergroup", ")", "PartitionOwner", "(", "topic", "string", ",", "partition", "int32", ")", "(", "*", "ConsumergroupInstance", ",", "error", ")", "{", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cg", ".", "Name", ",", "topic", ",", "partition", ")", "\n", "val", ",", "_", ",", "err", ":=", "cg", ".", "kz", ".", "conn", ".", "Get", "(", "node", ")", "\n\n", "// If the node does not exists, nobody has claimed it.", "switch", "err", "{", "case", "nil", ":", "return", "&", "ConsumergroupInstance", "{", "cg", ":", "cg", ",", "ID", ":", "string", "(", "val", ")", "}", ",", "nil", "\n", "case", "zk", ".", "ErrNoNode", ":", "return", "nil", ",", "nil", "\n", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n", "}" ]
// PartitionOwner returns the ConsumergroupInstance that has claimed the given partition. // This can be nil if nobody has claimed it yet.
[ "PartitionOwner", "returns", "the", "ConsumergroupInstance", "that", "has", "claimed", "the", "given", "partition", ".", "This", "can", "be", "nil", "if", "nobody", "has", "claimed", "it", "yet", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L166-L179
10,646
wvanbergen/kazoo-go
consumergroup.go
WatchPartitionOwner
func (cg *Consumergroup) WatchPartitionOwner(topic string, partition int32) (*ConsumergroupInstance, <-chan zk.Event, error) { node := fmt.Sprintf("%s/consumers/%s/owners/%s/%d", cg.kz.conf.Chroot, cg.Name, topic, partition) instanceID, _, changed, err := cg.kz.conn.GetW(node) switch err { case nil: return &ConsumergroupInstance{cg: cg, ID: string(instanceID)}, changed, nil case zk.ErrNoNode: return nil, nil, nil default: return nil, nil, err } }
go
func (cg *Consumergroup) WatchPartitionOwner(topic string, partition int32) (*ConsumergroupInstance, <-chan zk.Event, error) { node := fmt.Sprintf("%s/consumers/%s/owners/%s/%d", cg.kz.conf.Chroot, cg.Name, topic, partition) instanceID, _, changed, err := cg.kz.conn.GetW(node) switch err { case nil: return &ConsumergroupInstance{cg: cg, ID: string(instanceID)}, changed, nil case zk.ErrNoNode: return nil, nil, nil default: return nil, nil, err } }
[ "func", "(", "cg", "*", "Consumergroup", ")", "WatchPartitionOwner", "(", "topic", "string", ",", "partition", "int32", ")", "(", "*", "ConsumergroupInstance", ",", "<-", "chan", "zk", ".", "Event", ",", "error", ")", "{", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cg", ".", "Name", ",", "topic", ",", "partition", ")", "\n", "instanceID", ",", "_", ",", "changed", ",", "err", ":=", "cg", ".", "kz", ".", "conn", ".", "GetW", "(", "node", ")", "\n\n", "switch", "err", "{", "case", "nil", ":", "return", "&", "ConsumergroupInstance", "{", "cg", ":", "cg", ",", "ID", ":", "string", "(", "instanceID", ")", "}", ",", "changed", ",", "nil", "\n\n", "case", "zk", ".", "ErrNoNode", ":", "return", "nil", ",", "nil", ",", "nil", "\n\n", "default", ":", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "}" ]
// WatchPartitionOwner retrieves what instance is currently owning the partition, and sets a // Zookeeper watch to be notified of changes. If the partition currently does not have an owner, // the function returns nil for every return value. In this case is should be safe to claim // the partition for an instance.
[ "WatchPartitionOwner", "retrieves", "what", "instance", "is", "currently", "owning", "the", "partition", "and", "sets", "a", "Zookeeper", "watch", "to", "be", "notified", "of", "changes", ".", "If", "the", "partition", "currently", "does", "not", "have", "an", "owner", "the", "function", "returns", "nil", "for", "every", "return", "value", ".", "In", "this", "case", "is", "should", "be", "safe", "to", "claim", "the", "partition", "for", "an", "instance", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L185-L199
10,647
wvanbergen/kazoo-go
consumergroup.go
Registered
func (cgi *ConsumergroupInstance) Registered() (bool, error) { node := fmt.Sprintf("%s/consumers/%s/ids/%s", cgi.cg.kz.conf.Chroot, cgi.cg.Name, cgi.ID) return cgi.cg.kz.exists(node) }
go
func (cgi *ConsumergroupInstance) Registered() (bool, error) { node := fmt.Sprintf("%s/consumers/%s/ids/%s", cgi.cg.kz.conf.Chroot, cgi.cg.Name, cgi.ID) return cgi.cg.kz.exists(node) }
[ "func", "(", "cgi", "*", "ConsumergroupInstance", ")", "Registered", "(", ")", "(", "bool", ",", "error", ")", "{", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cgi", ".", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cgi", ".", "cg", ".", "Name", ",", "cgi", ".", "ID", ")", "\n", "return", "cgi", ".", "cg", ".", "kz", ".", "exists", "(", "node", ")", "\n", "}" ]
// Registered checks whether the consumergroup instance is registered in Zookeeper.
[ "Registered", "checks", "whether", "the", "consumergroup", "instance", "is", "registered", "in", "Zookeeper", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L202-L205
10,648
wvanbergen/kazoo-go
consumergroup.go
Registration
func (cgi *ConsumergroupInstance) Registration() (*Registration, error) { node := fmt.Sprintf("%s/consumers/%s/ids/%s", cgi.cg.kz.conf.Chroot, cgi.cg.Name, cgi.ID) val, _, err := cgi.cg.kz.conn.Get(node) if err != nil { if err == zk.ErrNoNode { return nil, ErrInstanceNotRegistered } return nil, err } reg := &Registration{} if err := json.Unmarshal(val, reg); err != nil { return nil, err } return reg, nil }
go
func (cgi *ConsumergroupInstance) Registration() (*Registration, error) { node := fmt.Sprintf("%s/consumers/%s/ids/%s", cgi.cg.kz.conf.Chroot, cgi.cg.Name, cgi.ID) val, _, err := cgi.cg.kz.conn.Get(node) if err != nil { if err == zk.ErrNoNode { return nil, ErrInstanceNotRegistered } return nil, err } reg := &Registration{} if err := json.Unmarshal(val, reg); err != nil { return nil, err } return reg, nil }
[ "func", "(", "cgi", "*", "ConsumergroupInstance", ")", "Registration", "(", ")", "(", "*", "Registration", ",", "error", ")", "{", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cgi", ".", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cgi", ".", "cg", ".", "Name", ",", "cgi", ".", "ID", ")", "\n", "val", ",", "_", ",", "err", ":=", "cgi", ".", "cg", ".", "kz", ".", "conn", ".", "Get", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "zk", ".", "ErrNoNode", "{", "return", "nil", ",", "ErrInstanceNotRegistered", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "reg", ":=", "&", "Registration", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "val", ",", "reg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "reg", ",", "nil", "\n", "}" ]
// Registered returns current registration of the consumer group instance.
[ "Registered", "returns", "current", "registration", "of", "the", "consumer", "group", "instance", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L208-L223
10,649
wvanbergen/kazoo-go
consumergroup.go
RegisterWithSubscription
func (cgi *ConsumergroupInstance) RegisterWithSubscription(subscriptionJSON []byte) error { node := fmt.Sprintf("%s/consumers/%s/ids/%s", cgi.cg.kz.conf.Chroot, cgi.cg.Name, cgi.ID) err := cgi.cg.kz.create(node, subscriptionJSON, true) if err == zk.ErrNodeExists { return ErrInstanceAlreadyRegistered } return err }
go
func (cgi *ConsumergroupInstance) RegisterWithSubscription(subscriptionJSON []byte) error { node := fmt.Sprintf("%s/consumers/%s/ids/%s", cgi.cg.kz.conf.Chroot, cgi.cg.Name, cgi.ID) err := cgi.cg.kz.create(node, subscriptionJSON, true) if err == zk.ErrNodeExists { return ErrInstanceAlreadyRegistered } return err }
[ "func", "(", "cgi", "*", "ConsumergroupInstance", ")", "RegisterWithSubscription", "(", "subscriptionJSON", "[", "]", "byte", ")", "error", "{", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cgi", ".", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cgi", ".", "cg", ".", "Name", ",", "cgi", ".", "ID", ")", "\n", "err", ":=", "cgi", ".", "cg", ".", "kz", ".", "create", "(", "node", ",", "subscriptionJSON", ",", "true", ")", "\n", "if", "err", "==", "zk", ".", "ErrNodeExists", "{", "return", "ErrInstanceAlreadyRegistered", "\n", "}", "\n", "return", "err", "\n", "}" ]
// RegisterSubscription registers the consumer instance in Zookeeper, with its subscription.
[ "RegisterSubscription", "registers", "the", "consumer", "instance", "in", "Zookeeper", "with", "its", "subscription", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L245-L252
10,650
wvanbergen/kazoo-go
consumergroup.go
UpdateRegistration
func (cgi *ConsumergroupInstance) UpdateRegistration(topics []string) error { subscriptionJSON, err := cgi.marshalSubscription(topics) if err != nil { return err } node := fmt.Sprintf("%s/consumers/%s/ids/%s", cgi.cg.kz.conf.Chroot, cgi.cg.Name, cgi.ID) _, stat, err := cgi.cg.kz.conn.Get(node) if err != nil { if err == zk.ErrNoNode { return ErrInstanceNotRegistered } return err } _, err = cgi.cg.kz.conn.Set(node, subscriptionJSON, stat.Version) if err == zk.ErrNoNode { return ErrInstanceNotRegistered } return err }
go
func (cgi *ConsumergroupInstance) UpdateRegistration(topics []string) error { subscriptionJSON, err := cgi.marshalSubscription(topics) if err != nil { return err } node := fmt.Sprintf("%s/consumers/%s/ids/%s", cgi.cg.kz.conf.Chroot, cgi.cg.Name, cgi.ID) _, stat, err := cgi.cg.kz.conn.Get(node) if err != nil { if err == zk.ErrNoNode { return ErrInstanceNotRegistered } return err } _, err = cgi.cg.kz.conn.Set(node, subscriptionJSON, stat.Version) if err == zk.ErrNoNode { return ErrInstanceNotRegistered } return err }
[ "func", "(", "cgi", "*", "ConsumergroupInstance", ")", "UpdateRegistration", "(", "topics", "[", "]", "string", ")", "error", "{", "subscriptionJSON", ",", "err", ":=", "cgi", ".", "marshalSubscription", "(", "topics", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cgi", ".", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cgi", ".", "cg", ".", "Name", ",", "cgi", ".", "ID", ")", "\n", "_", ",", "stat", ",", "err", ":=", "cgi", ".", "cg", ".", "kz", ".", "conn", ".", "Get", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "zk", ".", "ErrNoNode", "{", "return", "ErrInstanceNotRegistered", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "cgi", ".", "cg", ".", "kz", ".", "conn", ".", "Set", "(", "node", ",", "subscriptionJSON", ",", "stat", ".", "Version", ")", "\n", "if", "err", "==", "zk", ".", "ErrNoNode", "{", "return", "ErrInstanceNotRegistered", "\n", "}", "\n", "return", "err", "\n", "}" ]
// UpdateRegistration updates a consumer group member registration. If the // consumer group member has not been registered yet, then an error is returned.
[ "UpdateRegistration", "updates", "a", "consumer", "group", "member", "registration", ".", "If", "the", "consumer", "group", "member", "has", "not", "been", "registered", "yet", "then", "an", "error", "is", "returned", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L266-L286
10,651
wvanbergen/kazoo-go
consumergroup.go
Deregister
func (cgi *ConsumergroupInstance) Deregister() error { node := fmt.Sprintf("%s/consumers/%s/ids/%s", cgi.cg.kz.conf.Chroot, cgi.cg.Name, cgi.ID) exists, stat, err := cgi.cg.kz.conn.Exists(node) if err != nil { return err } else if !exists { return ErrInstanceNotRegistered } err = cgi.cg.kz.conn.Delete(node, stat.Version) if err == zk.ErrNoNode { return ErrInstanceNotRegistered } return err }
go
func (cgi *ConsumergroupInstance) Deregister() error { node := fmt.Sprintf("%s/consumers/%s/ids/%s", cgi.cg.kz.conf.Chroot, cgi.cg.Name, cgi.ID) exists, stat, err := cgi.cg.kz.conn.Exists(node) if err != nil { return err } else if !exists { return ErrInstanceNotRegistered } err = cgi.cg.kz.conn.Delete(node, stat.Version) if err == zk.ErrNoNode { return ErrInstanceNotRegistered } return err }
[ "func", "(", "cgi", "*", "ConsumergroupInstance", ")", "Deregister", "(", ")", "error", "{", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cgi", ".", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cgi", ".", "cg", ".", "Name", ",", "cgi", ".", "ID", ")", "\n", "exists", ",", "stat", ",", "err", ":=", "cgi", ".", "cg", ".", "kz", ".", "conn", ".", "Exists", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "!", "exists", "{", "return", "ErrInstanceNotRegistered", "\n", "}", "\n\n", "err", "=", "cgi", ".", "cg", ".", "kz", ".", "conn", ".", "Delete", "(", "node", ",", "stat", ".", "Version", ")", "\n", "if", "err", "==", "zk", ".", "ErrNoNode", "{", "return", "ErrInstanceNotRegistered", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Deregister removes the registration of the instance from zookeeper.
[ "Deregister", "removes", "the", "registration", "of", "the", "instance", "from", "zookeeper", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L307-L321
10,652
wvanbergen/kazoo-go
consumergroup.go
ReleasePartition
func (cgi *ConsumergroupInstance) ReleasePartition(topic string, partition int32) error { owner, err := cgi.cg.PartitionOwner(topic, partition) if err != nil { return err } if owner == nil || owner.ID != cgi.ID { return ErrPartitionNotClaimed } node := fmt.Sprintf("%s/consumers/%s/owners/%s/%d", cgi.cg.kz.conf.Chroot, cgi.cg.Name, topic, partition) return cgi.cg.kz.conn.Delete(node, 0) }
go
func (cgi *ConsumergroupInstance) ReleasePartition(topic string, partition int32) error { owner, err := cgi.cg.PartitionOwner(topic, partition) if err != nil { return err } if owner == nil || owner.ID != cgi.ID { return ErrPartitionNotClaimed } node := fmt.Sprintf("%s/consumers/%s/owners/%s/%d", cgi.cg.kz.conf.Chroot, cgi.cg.Name, topic, partition) return cgi.cg.kz.conn.Delete(node, 0) }
[ "func", "(", "cgi", "*", "ConsumergroupInstance", ")", "ReleasePartition", "(", "topic", "string", ",", "partition", "int32", ")", "error", "{", "owner", ",", "err", ":=", "cgi", ".", "cg", ".", "PartitionOwner", "(", "topic", ",", "partition", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "owner", "==", "nil", "||", "owner", ".", "ID", "!=", "cgi", ".", "ID", "{", "return", "ErrPartitionNotClaimed", "\n", "}", "\n\n", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cgi", ".", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cgi", ".", "cg", ".", "Name", ",", "topic", ",", "partition", ")", "\n", "return", "cgi", ".", "cg", ".", "kz", ".", "conn", ".", "Delete", "(", "node", ",", "0", ")", "\n", "}" ]
// ReleasePartition releases a claim to a partition.
[ "ReleasePartition", "releases", "a", "claim", "to", "a", "partition", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L351-L362
10,653
wvanbergen/kazoo-go
consumergroup.go
FetchAllOffsets
func (cg *Consumergroup) FetchAllOffsets() (map[string]map[int32]int64, error) { result := make(map[string]map[int32]int64) offsetsNode := fmt.Sprintf("%s/consumers/%s/offsets", cg.kz.conf.Chroot, cg.Name) topics, _, err := cg.kz.conn.Children(offsetsNode) if err == zk.ErrNoNode { return result, nil } else if err != nil { return nil, err } for _, topic := range topics { result[topic] = make(map[int32]int64) topicNode := fmt.Sprintf("%s/consumers/%s/offsets/%s", cg.kz.conf.Chroot, cg.Name, topic) partitions, _, err := cg.kz.conn.Children(topicNode) if err != nil { return nil, err } for _, partition := range partitions { partitionNode := fmt.Sprintf("%s/consumers/%s/offsets/%s/%s", cg.kz.conf.Chroot, cg.Name, topic, partition) val, _, err := cg.kz.conn.Get(partitionNode) if err != nil { return nil, err } partition, err := strconv.ParseInt(partition, 10, 32) if err != nil { return nil, err } offset, err := strconv.ParseInt(string(val), 10, 64) if err != nil { return nil, err } result[topic][int32(partition)] = offset } } return result, nil }
go
func (cg *Consumergroup) FetchAllOffsets() (map[string]map[int32]int64, error) { result := make(map[string]map[int32]int64) offsetsNode := fmt.Sprintf("%s/consumers/%s/offsets", cg.kz.conf.Chroot, cg.Name) topics, _, err := cg.kz.conn.Children(offsetsNode) if err == zk.ErrNoNode { return result, nil } else if err != nil { return nil, err } for _, topic := range topics { result[topic] = make(map[int32]int64) topicNode := fmt.Sprintf("%s/consumers/%s/offsets/%s", cg.kz.conf.Chroot, cg.Name, topic) partitions, _, err := cg.kz.conn.Children(topicNode) if err != nil { return nil, err } for _, partition := range partitions { partitionNode := fmt.Sprintf("%s/consumers/%s/offsets/%s/%s", cg.kz.conf.Chroot, cg.Name, topic, partition) val, _, err := cg.kz.conn.Get(partitionNode) if err != nil { return nil, err } partition, err := strconv.ParseInt(partition, 10, 32) if err != nil { return nil, err } offset, err := strconv.ParseInt(string(val), 10, 64) if err != nil { return nil, err } result[topic][int32(partition)] = offset } } return result, nil }
[ "func", "(", "cg", "*", "Consumergroup", ")", "FetchAllOffsets", "(", ")", "(", "map", "[", "string", "]", "map", "[", "int32", "]", "int64", ",", "error", ")", "{", "result", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "int32", "]", "int64", ")", "\n\n", "offsetsNode", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cg", ".", "Name", ")", "\n", "topics", ",", "_", ",", "err", ":=", "cg", ".", "kz", ".", "conn", ".", "Children", "(", "offsetsNode", ")", "\n", "if", "err", "==", "zk", ".", "ErrNoNode", "{", "return", "result", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "topic", ":=", "range", "topics", "{", "result", "[", "topic", "]", "=", "make", "(", "map", "[", "int32", "]", "int64", ")", "\n", "topicNode", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cg", ".", "Name", ",", "topic", ")", "\n", "partitions", ",", "_", ",", "err", ":=", "cg", ".", "kz", ".", "conn", ".", "Children", "(", "topicNode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "partition", ":=", "range", "partitions", "{", "partitionNode", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cg", ".", "kz", ".", "conf", ".", "Chroot", ",", "cg", ".", "Name", ",", "topic", ",", "partition", ")", "\n", "val", ",", "_", ",", "err", ":=", "cg", ".", "kz", ".", "conn", ".", "Get", "(", "partitionNode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "partition", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "partition", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "offset", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "string", "(", "val", ")", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "result", "[", "topic", "]", "[", "int32", "(", "partition", ")", "]", "=", "offset", "\n", "}", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// FetchOffset retrieves all the commmitted offsets for a group
[ "FetchOffset", "retrieves", "all", "the", "commmitted", "offsets", "for", "a", "group" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L411-L452
10,654
wvanbergen/kazoo-go
consumergroup.go
generateConsumerInstanceID
func generateConsumerInstanceID() (string, error) { uuid, err := generateUUID() if err != nil { return "", err } hostname, err := os.Hostname() if err != nil { return "", err } return fmt.Sprintf("%s:%s", hostname, uuid), nil }
go
func generateConsumerInstanceID() (string, error) { uuid, err := generateUUID() if err != nil { return "", err } hostname, err := os.Hostname() if err != nil { return "", err } return fmt.Sprintf("%s:%s", hostname, uuid), nil }
[ "func", "generateConsumerInstanceID", "(", ")", "(", "string", ",", "error", ")", "{", "uuid", ",", "err", ":=", "generateUUID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "hostname", ",", "err", ":=", "os", ".", "Hostname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hostname", ",", "uuid", ")", ",", "nil", "\n", "}" ]
// generateConsumerInstanceID generates a consumergroup Instance ID // that is almost certain to be unique.
[ "generateConsumerInstanceID", "generates", "a", "consumergroup", "Instance", "ID", "that", "is", "almost", "certain", "to", "be", "unique", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L508-L520
10,655
wvanbergen/kazoo-go
consumergroup.go
Find
func (cgl ConsumergroupList) Find(name string) *Consumergroup { for _, cg := range cgl { if cg.Name == name { return cg } } return nil }
go
func (cgl ConsumergroupList) Find(name string) *Consumergroup { for _, cg := range cgl { if cg.Name == name { return cg } } return nil }
[ "func", "(", "cgl", "ConsumergroupList", ")", "Find", "(", "name", "string", ")", "*", "Consumergroup", "{", "for", "_", ",", "cg", ":=", "range", "cgl", "{", "if", "cg", ".", "Name", "==", "name", "{", "return", "cg", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Find returns the consumergroup with the given name if it exists in the list. // Otherwise it will return `nil`.
[ "Find", "returns", "the", "consumergroup", "with", "the", "given", "name", "if", "it", "exists", "in", "the", "list", ".", "Otherwise", "it", "will", "return", "nil", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L524-L531
10,656
wvanbergen/kazoo-go
consumergroup.go
Find
func (cgil ConsumergroupInstanceList) Find(id string) *ConsumergroupInstance { for _, cgi := range cgil { if cgi.ID == id { return cgi } } return nil }
go
func (cgil ConsumergroupInstanceList) Find(id string) *ConsumergroupInstance { for _, cgi := range cgil { if cgi.ID == id { return cgi } } return nil }
[ "func", "(", "cgil", "ConsumergroupInstanceList", ")", "Find", "(", "id", "string", ")", "*", "ConsumergroupInstance", "{", "for", "_", ",", "cgi", ":=", "range", "cgil", "{", "if", "cgi", ".", "ID", "==", "id", "{", "return", "cgi", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Find returns the consumergroup instance with the given ID if it exists in the list. // Otherwise it will return `nil`.
[ "Find", "returns", "the", "consumergroup", "instance", "with", "the", "given", "ID", "if", "it", "exists", "in", "the", "list", ".", "Otherwise", "it", "will", "return", "nil", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/consumergroup.go#L547-L554
10,657
wvanbergen/kazoo-go
topic_metadata.go
Topics
func (kz *Kazoo) Topics() (TopicList, error) { root := fmt.Sprintf("%s/brokers/topics", kz.conf.Chroot) children, _, err := kz.conn.Children(root) if err != nil { return nil, err } result := make(TopicList, 0, len(children)) for _, name := range children { result = append(result, kz.Topic(name)) } return result, nil }
go
func (kz *Kazoo) Topics() (TopicList, error) { root := fmt.Sprintf("%s/brokers/topics", kz.conf.Chroot) children, _, err := kz.conn.Children(root) if err != nil { return nil, err } result := make(TopicList, 0, len(children)) for _, name := range children { result = append(result, kz.Topic(name)) } return result, nil }
[ "func", "(", "kz", "*", "Kazoo", ")", "Topics", "(", ")", "(", "TopicList", ",", "error", ")", "{", "root", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "kz", ".", "conf", ".", "Chroot", ")", "\n", "children", ",", "_", ",", "err", ":=", "kz", ".", "conn", ".", "Children", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "result", ":=", "make", "(", "TopicList", ",", "0", ",", "len", "(", "children", ")", ")", "\n", "for", "_", ",", "name", ":=", "range", "children", "{", "result", "=", "append", "(", "result", ",", "kz", ".", "Topic", "(", "name", ")", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Topics returns a list of all registered Kafka topics.
[ "Topics", "returns", "a", "list", "of", "all", "registered", "Kafka", "topics", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L43-L55
10,658
wvanbergen/kazoo-go
topic_metadata.go
WatchTopics
func (kz *Kazoo) WatchTopics() (TopicList, <-chan zk.Event, error) { root := fmt.Sprintf("%s/brokers/topics", kz.conf.Chroot) children, _, c, err := kz.conn.ChildrenW(root) if err != nil { return nil, nil, err } result := make(TopicList, 0, len(children)) for _, name := range children { result = append(result, kz.Topic(name)) } return result, c, nil }
go
func (kz *Kazoo) WatchTopics() (TopicList, <-chan zk.Event, error) { root := fmt.Sprintf("%s/brokers/topics", kz.conf.Chroot) children, _, c, err := kz.conn.ChildrenW(root) if err != nil { return nil, nil, err } result := make(TopicList, 0, len(children)) for _, name := range children { result = append(result, kz.Topic(name)) } return result, c, nil }
[ "func", "(", "kz", "*", "Kazoo", ")", "WatchTopics", "(", ")", "(", "TopicList", ",", "<-", "chan", "zk", ".", "Event", ",", "error", ")", "{", "root", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "kz", ".", "conf", ".", "Chroot", ")", "\n", "children", ",", "_", ",", "c", ",", "err", ":=", "kz", ".", "conn", ".", "ChildrenW", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "result", ":=", "make", "(", "TopicList", ",", "0", ",", "len", "(", "children", ")", ")", "\n", "for", "_", ",", "name", ":=", "range", "children", "{", "result", "=", "append", "(", "result", ",", "kz", ".", "Topic", "(", "name", ")", ")", "\n", "}", "\n", "return", "result", ",", "c", ",", "nil", "\n", "}" ]
// WatchTopics returns a list of all registered Kafka topics, and // watches that list for changes.
[ "WatchTopics", "returns", "a", "list", "of", "all", "registered", "Kafka", "topics", "and", "watches", "that", "list", "for", "changes", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L59-L71
10,659
wvanbergen/kazoo-go
topic_metadata.go
Topic
func (kz *Kazoo) Topic(topic string) *Topic { return &Topic{Name: topic, kz: kz} }
go
func (kz *Kazoo) Topic(topic string) *Topic { return &Topic{Name: topic, kz: kz} }
[ "func", "(", "kz", "*", "Kazoo", ")", "Topic", "(", "topic", "string", ")", "*", "Topic", "{", "return", "&", "Topic", "{", "Name", ":", "topic", ",", "kz", ":", "kz", "}", "\n", "}" ]
// Topic returns a Topic instance for a given topic name
[ "Topic", "returns", "a", "Topic", "instance", "for", "a", "given", "topic", "name" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L74-L76
10,660
wvanbergen/kazoo-go
topic_metadata.go
Exists
func (t *Topic) Exists() (bool, error) { return t.kz.exists(t.metadataPath()) }
go
func (t *Topic) Exists() (bool, error) { return t.kz.exists(t.metadataPath()) }
[ "func", "(", "t", "*", "Topic", ")", "Exists", "(", ")", "(", "bool", ",", "error", ")", "{", "return", "t", ".", "kz", ".", "exists", "(", "t", ".", "metadataPath", "(", ")", ")", "\n", "}" ]
// Exists returns true if the topic exists on the Kafka cluster.
[ "Exists", "returns", "true", "if", "the", "topic", "exists", "on", "the", "Kafka", "cluster", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L79-L81
10,661
wvanbergen/kazoo-go
topic_metadata.go
Partitions
func (t *Topic) Partitions() (PartitionList, error) { value, _, err := t.kz.conn.Get(t.metadataPath()) if err != nil { return nil, err } return t.parsePartitions(value) }
go
func (t *Topic) Partitions() (PartitionList, error) { value, _, err := t.kz.conn.Get(t.metadataPath()) if err != nil { return nil, err } return t.parsePartitions(value) }
[ "func", "(", "t", "*", "Topic", ")", "Partitions", "(", ")", "(", "PartitionList", ",", "error", ")", "{", "value", ",", "_", ",", "err", ":=", "t", ".", "kz", ".", "conn", ".", "Get", "(", "t", ".", "metadataPath", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "t", ".", "parsePartitions", "(", "value", ")", "\n", "}" ]
// Partitions returns a list of all partitions for the topic.
[ "Partitions", "returns", "a", "list", "of", "all", "partitions", "for", "the", "topic", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L84-L91
10,662
wvanbergen/kazoo-go
topic_metadata.go
WatchPartitions
func (t *Topic) WatchPartitions() (PartitionList, <-chan zk.Event, error) { value, _, c, err := t.kz.conn.GetW(t.metadataPath()) if err != nil { return nil, nil, err } list, err := t.parsePartitions(value) return list, c, err }
go
func (t *Topic) WatchPartitions() (PartitionList, <-chan zk.Event, error) { value, _, c, err := t.kz.conn.GetW(t.metadataPath()) if err != nil { return nil, nil, err } list, err := t.parsePartitions(value) return list, c, err }
[ "func", "(", "t", "*", "Topic", ")", "WatchPartitions", "(", ")", "(", "PartitionList", ",", "<-", "chan", "zk", ".", "Event", ",", "error", ")", "{", "value", ",", "_", ",", "c", ",", "err", ":=", "t", ".", "kz", ".", "conn", ".", "GetW", "(", "t", ".", "metadataPath", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "list", ",", "err", ":=", "t", ".", "parsePartitions", "(", "value", ")", "\n", "return", "list", ",", "c", ",", "err", "\n", "}" ]
// WatchPartitions returns a list of all partitions for the topic, and watches the topic for changes.
[ "WatchPartitions", "returns", "a", "list", "of", "all", "partitions", "for", "the", "topic", "and", "watches", "the", "topic", "for", "changes", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L94-L102
10,663
wvanbergen/kazoo-go
topic_metadata.go
Watch
func (t *Topic) Watch() (<-chan zk.Event, error) { _, _, c, err := t.kz.conn.GetW(t.metadataPath()) if err != nil { return nil, err } return c, err }
go
func (t *Topic) Watch() (<-chan zk.Event, error) { _, _, c, err := t.kz.conn.GetW(t.metadataPath()) if err != nil { return nil, err } return c, err }
[ "func", "(", "t", "*", "Topic", ")", "Watch", "(", ")", "(", "<-", "chan", "zk", ".", "Event", ",", "error", ")", "{", "_", ",", "_", ",", "c", ",", "err", ":=", "t", ".", "kz", ".", "conn", ".", "GetW", "(", "t", ".", "metadataPath", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "c", ",", "err", "\n", "}" ]
// Watch watches the topic for changes.
[ "Watch", "watches", "the", "topic", "for", "changes", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L105-L112
10,664
wvanbergen/kazoo-go
topic_metadata.go
parsePartitions
func (t *Topic) parsePartitions(value []byte) (PartitionList, error) { var tm topicMetadata if err := json.Unmarshal(value, &tm); err != nil { return nil, err } result := make(PartitionList, len(tm.Partitions)) for partitionNumber, replicas := range tm.Partitions { partitionID, err := strconv.ParseInt(partitionNumber, 10, 32) if err != nil { return nil, err } replicaIDs := make([]int32, 0, len(replicas)) for _, r := range replicas { replicaIDs = append(replicaIDs, int32(r)) } result[partitionID] = t.Partition(int32(partitionID), replicaIDs) } return result, nil }
go
func (t *Topic) parsePartitions(value []byte) (PartitionList, error) { var tm topicMetadata if err := json.Unmarshal(value, &tm); err != nil { return nil, err } result := make(PartitionList, len(tm.Partitions)) for partitionNumber, replicas := range tm.Partitions { partitionID, err := strconv.ParseInt(partitionNumber, 10, 32) if err != nil { return nil, err } replicaIDs := make([]int32, 0, len(replicas)) for _, r := range replicas { replicaIDs = append(replicaIDs, int32(r)) } result[partitionID] = t.Partition(int32(partitionID), replicaIDs) } return result, nil }
[ "func", "(", "t", "*", "Topic", ")", "parsePartitions", "(", "value", "[", "]", "byte", ")", "(", "PartitionList", ",", "error", ")", "{", "var", "tm", "topicMetadata", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "value", ",", "&", "tm", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "result", ":=", "make", "(", "PartitionList", ",", "len", "(", "tm", ".", "Partitions", ")", ")", "\n", "for", "partitionNumber", ",", "replicas", ":=", "range", "tm", ".", "Partitions", "{", "partitionID", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "partitionNumber", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "replicaIDs", ":=", "make", "(", "[", "]", "int32", ",", "0", ",", "len", "(", "replicas", ")", ")", "\n", "for", "_", ",", "r", ":=", "range", "replicas", "{", "replicaIDs", "=", "append", "(", "replicaIDs", ",", "int32", "(", "r", ")", ")", "\n", "}", "\n", "result", "[", "partitionID", "]", "=", "t", ".", "Partition", "(", "int32", "(", "partitionID", ")", ",", "replicaIDs", ")", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// parsePartitions parses the JSON representation of the partitions // that is stored as data on the topic node in Zookeeper.
[ "parsePartitions", "parses", "the", "JSON", "representation", "of", "the", "partitions", "that", "is", "stored", "as", "data", "on", "the", "topic", "node", "in", "Zookeeper", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L125-L146
10,665
wvanbergen/kazoo-go
topic_metadata.go
marshalPartitions
func (t *Topic) marshalPartitions(partitions PartitionList) ([]byte, error) { tm := topicMetadata{Version: 1, Partitions: make(map[string][]int32, len(partitions))} for _, part := range partitions { tm.Partitions[fmt.Sprintf("%d", part.ID)] = part.Replicas } return json.Marshal(tm) }
go
func (t *Topic) marshalPartitions(partitions PartitionList) ([]byte, error) { tm := topicMetadata{Version: 1, Partitions: make(map[string][]int32, len(partitions))} for _, part := range partitions { tm.Partitions[fmt.Sprintf("%d", part.ID)] = part.Replicas } return json.Marshal(tm) }
[ "func", "(", "t", "*", "Topic", ")", "marshalPartitions", "(", "partitions", "PartitionList", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "tm", ":=", "topicMetadata", "{", "Version", ":", "1", ",", "Partitions", ":", "make", "(", "map", "[", "string", "]", "[", "]", "int32", ",", "len", "(", "partitions", ")", ")", "}", "\n", "for", "_", ",", "part", ":=", "range", "partitions", "{", "tm", ".", "Partitions", "[", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "part", ".", "ID", ")", "]", "=", "part", ".", "Replicas", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "tm", ")", "\n", "}" ]
// marshalPartitions turns a PartitionList into the JSON representation // to be stored in Zookeeper.
[ "marshalPartitions", "turns", "a", "PartitionList", "into", "the", "JSON", "representation", "to", "be", "stored", "in", "Zookeeper", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L150-L156
10,666
wvanbergen/kazoo-go
topic_metadata.go
generatePartitionAssignments
func (t *Topic) generatePartitionAssignments(brokers []int32, partitionCount int, replicationFactor int) (PartitionList, error) { if partitionCount <= 0 { return nil, ErrInvalidPartitionCount } if replicationFactor <= 0 || len(brokers) < replicationFactor { return nil, ErrInvalidReplicationFactor } result := make(PartitionList, partitionCount) brokerCount := len(brokers) brokerIdx := rand.Intn(brokerCount) for p := 0; p < partitionCount; p++ { partition := &Partition{topic: t, ID: int32(p), Replicas: make([]int32, replicationFactor)} brokerIndices := rand.Perm(len(brokers))[0:replicationFactor] for r := 0; r < replicationFactor; r++ { partition.Replicas[r] = brokers[brokerIndices[r]] } result[p] = partition brokerIdx = (brokerIdx + 1) % brokerCount } return result, nil }
go
func (t *Topic) generatePartitionAssignments(brokers []int32, partitionCount int, replicationFactor int) (PartitionList, error) { if partitionCount <= 0 { return nil, ErrInvalidPartitionCount } if replicationFactor <= 0 || len(brokers) < replicationFactor { return nil, ErrInvalidReplicationFactor } result := make(PartitionList, partitionCount) brokerCount := len(brokers) brokerIdx := rand.Intn(brokerCount) for p := 0; p < partitionCount; p++ { partition := &Partition{topic: t, ID: int32(p), Replicas: make([]int32, replicationFactor)} brokerIndices := rand.Perm(len(brokers))[0:replicationFactor] for r := 0; r < replicationFactor; r++ { partition.Replicas[r] = brokers[brokerIndices[r]] } result[p] = partition brokerIdx = (brokerIdx + 1) % brokerCount } return result, nil }
[ "func", "(", "t", "*", "Topic", ")", "generatePartitionAssignments", "(", "brokers", "[", "]", "int32", ",", "partitionCount", "int", ",", "replicationFactor", "int", ")", "(", "PartitionList", ",", "error", ")", "{", "if", "partitionCount", "<=", "0", "{", "return", "nil", ",", "ErrInvalidPartitionCount", "\n", "}", "\n", "if", "replicationFactor", "<=", "0", "||", "len", "(", "brokers", ")", "<", "replicationFactor", "{", "return", "nil", ",", "ErrInvalidReplicationFactor", "\n", "}", "\n\n", "result", ":=", "make", "(", "PartitionList", ",", "partitionCount", ")", "\n\n", "brokerCount", ":=", "len", "(", "brokers", ")", "\n", "brokerIdx", ":=", "rand", ".", "Intn", "(", "brokerCount", ")", "\n\n", "for", "p", ":=", "0", ";", "p", "<", "partitionCount", ";", "p", "++", "{", "partition", ":=", "&", "Partition", "{", "topic", ":", "t", ",", "ID", ":", "int32", "(", "p", ")", ",", "Replicas", ":", "make", "(", "[", "]", "int32", ",", "replicationFactor", ")", "}", "\n\n", "brokerIndices", ":=", "rand", ".", "Perm", "(", "len", "(", "brokers", ")", ")", "[", "0", ":", "replicationFactor", "]", "\n\n", "for", "r", ":=", "0", ";", "r", "<", "replicationFactor", ";", "r", "++", "{", "partition", ".", "Replicas", "[", "r", "]", "=", "brokers", "[", "brokerIndices", "[", "r", "]", "]", "\n", "}", "\n\n", "result", "[", "p", "]", "=", "partition", "\n", "brokerIdx", "=", "(", "brokerIdx", "+", "1", ")", "%", "brokerCount", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// generatePartitionAssignments creates a partition list for a topic. The primary replica for // each partition is assigned in a round-robin fashion starting at a random broker. // Additional replicas are assigned to subsequent brokers to ensure there is no overlap
[ "generatePartitionAssignments", "creates", "a", "partition", "list", "for", "a", "topic", ".", "The", "primary", "replica", "for", "each", "partition", "is", "assigned", "in", "a", "round", "-", "robin", "fashion", "starting", "at", "a", "random", "broker", ".", "Additional", "replicas", "are", "assigned", "to", "subsequent", "brokers", "to", "ensure", "there", "is", "no", "overlap" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L161-L188
10,667
wvanbergen/kazoo-go
topic_metadata.go
validatePartitionAssignments
func (t *Topic) validatePartitionAssignments(brokers []int32, assignment PartitionList) error { if len(assignment) == 0 { return ErrInvalidPartitionCount } // get the first replica count to compare against. Every partition should have the same. var replicaCount int for _, part := range assignment { replicaCount = len(part.Replicas) break } if replicaCount == 0 { return ErrInvalidReplicationFactor } // ensure all ids are unique and sequential maxPartitionID := int32(-1) partitionIDmap := make(map[int32]struct{}, len(assignment)) for _, part := range assignment { if part == nil { continue } if maxPartitionID < part.ID { maxPartitionID = part.ID } partitionIDmap[part.ID] = struct{}{} // all partitions require the same replica count if len(part.Replicas) != replicaCount { return ErrInvalidReplicaCount } rset := make(map[int32]struct{}, replicaCount) for _, r := range part.Replicas { // replica must be assigned to a valid broker found := false for _, b := range brokers { if r == b { found = true break } } if !found { return ErrInvalidBroker } rset[r] = struct{}{} } // broker assignments for a partition must be unique if len(rset) != replicaCount { return ErrReplicaBrokerOverlap } } // ensure all partitions accounted for if int(maxPartitionID) != len(assignment)-1 { return ErrMissingPartitionID } // ensure no duplicate ids if len(partitionIDmap) != len(assignment) { return ErrDuplicatePartitionID } return nil }
go
func (t *Topic) validatePartitionAssignments(brokers []int32, assignment PartitionList) error { if len(assignment) == 0 { return ErrInvalidPartitionCount } // get the first replica count to compare against. Every partition should have the same. var replicaCount int for _, part := range assignment { replicaCount = len(part.Replicas) break } if replicaCount == 0 { return ErrInvalidReplicationFactor } // ensure all ids are unique and sequential maxPartitionID := int32(-1) partitionIDmap := make(map[int32]struct{}, len(assignment)) for _, part := range assignment { if part == nil { continue } if maxPartitionID < part.ID { maxPartitionID = part.ID } partitionIDmap[part.ID] = struct{}{} // all partitions require the same replica count if len(part.Replicas) != replicaCount { return ErrInvalidReplicaCount } rset := make(map[int32]struct{}, replicaCount) for _, r := range part.Replicas { // replica must be assigned to a valid broker found := false for _, b := range brokers { if r == b { found = true break } } if !found { return ErrInvalidBroker } rset[r] = struct{}{} } // broker assignments for a partition must be unique if len(rset) != replicaCount { return ErrReplicaBrokerOverlap } } // ensure all partitions accounted for if int(maxPartitionID) != len(assignment)-1 { return ErrMissingPartitionID } // ensure no duplicate ids if len(partitionIDmap) != len(assignment) { return ErrDuplicatePartitionID } return nil }
[ "func", "(", "t", "*", "Topic", ")", "validatePartitionAssignments", "(", "brokers", "[", "]", "int32", ",", "assignment", "PartitionList", ")", "error", "{", "if", "len", "(", "assignment", ")", "==", "0", "{", "return", "ErrInvalidPartitionCount", "\n", "}", "\n\n", "// get the first replica count to compare against. Every partition should have the same.", "var", "replicaCount", "int", "\n", "for", "_", ",", "part", ":=", "range", "assignment", "{", "replicaCount", "=", "len", "(", "part", ".", "Replicas", ")", "\n", "break", "\n", "}", "\n", "if", "replicaCount", "==", "0", "{", "return", "ErrInvalidReplicationFactor", "\n", "}", "\n\n", "// ensure all ids are unique and sequential", "maxPartitionID", ":=", "int32", "(", "-", "1", ")", "\n", "partitionIDmap", ":=", "make", "(", "map", "[", "int32", "]", "struct", "{", "}", ",", "len", "(", "assignment", ")", ")", "\n\n", "for", "_", ",", "part", ":=", "range", "assignment", "{", "if", "part", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "maxPartitionID", "<", "part", ".", "ID", "{", "maxPartitionID", "=", "part", ".", "ID", "\n", "}", "\n", "partitionIDmap", "[", "part", ".", "ID", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "// all partitions require the same replica count", "if", "len", "(", "part", ".", "Replicas", ")", "!=", "replicaCount", "{", "return", "ErrInvalidReplicaCount", "\n", "}", "\n\n", "rset", ":=", "make", "(", "map", "[", "int32", "]", "struct", "{", "}", ",", "replicaCount", ")", "\n", "for", "_", ",", "r", ":=", "range", "part", ".", "Replicas", "{", "// replica must be assigned to a valid broker", "found", ":=", "false", "\n", "for", "_", ",", "b", ":=", "range", "brokers", "{", "if", "r", "==", "b", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "return", "ErrInvalidBroker", "\n", "}", "\n", "rset", "[", "r", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "// broker assignments for a partition must be unique", "if", "len", "(", "rset", ")", "!=", "replicaCount", "{", "return", "ErrReplicaBrokerOverlap", "\n", "}", "\n", "}", "\n\n", "// ensure all partitions accounted for", "if", "int", "(", "maxPartitionID", ")", "!=", "len", "(", "assignment", ")", "-", "1", "{", "return", "ErrMissingPartitionID", "\n", "}", "\n\n", "// ensure no duplicate ids", "if", "len", "(", "partitionIDmap", ")", "!=", "len", "(", "assignment", ")", "{", "return", "ErrDuplicatePartitionID", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validatePartitionAssignments ensures that all partitions are assigned to valid brokers, // have the same number of replicas, and each replica is assigned to a unique broker
[ "validatePartitionAssignments", "ensures", "that", "all", "partitions", "are", "assigned", "to", "valid", "brokers", "have", "the", "same", "number", "of", "replicas", "and", "each", "replica", "is", "assigned", "to", "a", "unique", "broker" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L192-L257
10,668
wvanbergen/kazoo-go
topic_metadata.go
Partition
func (t *Topic) Partition(id int32, replicas []int32) *Partition { return &Partition{ID: id, Replicas: replicas, topic: t} }
go
func (t *Topic) Partition(id int32, replicas []int32) *Partition { return &Partition{ID: id, Replicas: replicas, topic: t} }
[ "func", "(", "t", "*", "Topic", ")", "Partition", "(", "id", "int32", ",", "replicas", "[", "]", "int32", ")", "*", "Partition", "{", "return", "&", "Partition", "{", "ID", ":", "id", ",", "Replicas", ":", "replicas", ",", "topic", ":", "t", "}", "\n", "}" ]
// Partition returns a Partition instance for the topic.
[ "Partition", "returns", "a", "Partition", "instance", "for", "the", "topic", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L260-L262
10,669
wvanbergen/kazoo-go
topic_metadata.go
configPath
func (t *Topic) configPath() string { return fmt.Sprintf("%s/config/topics/%s", t.kz.conf.Chroot, t.Name) }
go
func (t *Topic) configPath() string { return fmt.Sprintf("%s/config/topics/%s", t.kz.conf.Chroot, t.Name) }
[ "func", "(", "t", "*", "Topic", ")", "configPath", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "kz", ".", "conf", ".", "Chroot", ",", "t", ".", "Name", ")", "\n", "}" ]
// getConfigPath returns the zk node path for a topic's config
[ "getConfigPath", "returns", "the", "zk", "node", "path", "for", "a", "topic", "s", "config" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L270-L272
10,670
wvanbergen/kazoo-go
topic_metadata.go
parseConfig
func (t *Topic) parseConfig(data []byte) (map[string]string, error) { var cfg topicConfig if err := json.Unmarshal(data, &cfg); err != nil { return nil, err } return cfg.ConfigMap, nil }
go
func (t *Topic) parseConfig(data []byte) (map[string]string, error) { var cfg topicConfig if err := json.Unmarshal(data, &cfg); err != nil { return nil, err } return cfg.ConfigMap, nil }
[ "func", "(", "t", "*", "Topic", ")", "parseConfig", "(", "data", "[", "]", "byte", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "var", "cfg", "topicConfig", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "cfg", ".", "ConfigMap", ",", "nil", "\n", "}" ]
// parseConfig parses the json representation of a topic config // and returns the configuration values
[ "parseConfig", "parses", "the", "json", "representation", "of", "a", "topic", "config", "and", "returns", "the", "configuration", "values" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L276-L282
10,671
wvanbergen/kazoo-go
topic_metadata.go
marshalConfig
func (t *Topic) marshalConfig(data map[string]string) ([]byte, error) { cfg := topicConfig{Version: 1, ConfigMap: data} if cfg.ConfigMap == nil { cfg.ConfigMap = make(map[string]string) } return json.Marshal(&cfg) }
go
func (t *Topic) marshalConfig(data map[string]string) ([]byte, error) { cfg := topicConfig{Version: 1, ConfigMap: data} if cfg.ConfigMap == nil { cfg.ConfigMap = make(map[string]string) } return json.Marshal(&cfg) }
[ "func", "(", "t", "*", "Topic", ")", "marshalConfig", "(", "data", "map", "[", "string", "]", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cfg", ":=", "topicConfig", "{", "Version", ":", "1", ",", "ConfigMap", ":", "data", "}", "\n", "if", "cfg", ".", "ConfigMap", "==", "nil", "{", "cfg", ".", "ConfigMap", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "&", "cfg", ")", "\n", "}" ]
// marshalConfig turns a config map into the json representation // needed for Zookeeper
[ "marshalConfig", "turns", "a", "config", "map", "into", "the", "json", "representation", "needed", "for", "Zookeeper" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L286-L292
10,672
wvanbergen/kazoo-go
topic_metadata.go
Config
func (t *Topic) Config() (map[string]string, error) { value, _, err := t.kz.conn.Get(t.configPath()) if err != nil { return nil, err } return t.parseConfig(value) }
go
func (t *Topic) Config() (map[string]string, error) { value, _, err := t.kz.conn.Get(t.configPath()) if err != nil { return nil, err } return t.parseConfig(value) }
[ "func", "(", "t", "*", "Topic", ")", "Config", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "value", ",", "_", ",", "err", ":=", "t", ".", "kz", ".", "conn", ".", "Get", "(", "t", ".", "configPath", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "t", ".", "parseConfig", "(", "value", ")", "\n", "}" ]
// Config returns topic-level configuration settings as a map.
[ "Config", "returns", "topic", "-", "level", "configuration", "settings", "as", "a", "map", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L295-L302
10,673
wvanbergen/kazoo-go
topic_metadata.go
Leader
func (p *Partition) Leader() (int32, error) { if state, err := p.state(); err != nil { return -1, err } else { return state.Leader, nil } }
go
func (p *Partition) Leader() (int32, error) { if state, err := p.state(); err != nil { return -1, err } else { return state.Leader, nil } }
[ "func", "(", "p", "*", "Partition", ")", "Leader", "(", ")", "(", "int32", ",", "error", ")", "{", "if", "state", ",", "err", ":=", "p", ".", "state", "(", ")", ";", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "else", "{", "return", "state", ".", "Leader", ",", "nil", "\n", "}", "\n", "}" ]
// Leader returns the broker ID of the broker that is currently the leader for the partition.
[ "Leader", "returns", "the", "broker", "ID", "of", "the", "broker", "that", "is", "currently", "the", "leader", "for", "the", "partition", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L324-L330
10,674
wvanbergen/kazoo-go
topic_metadata.go
ISR
func (p *Partition) ISR() ([]int32, error) { if state, err := p.state(); err != nil { return nil, err } else { return state.ISR, nil } }
go
func (p *Partition) ISR() ([]int32, error) { if state, err := p.state(); err != nil { return nil, err } else { return state.ISR, nil } }
[ "func", "(", "p", "*", "Partition", ")", "ISR", "(", ")", "(", "[", "]", "int32", ",", "error", ")", "{", "if", "state", ",", "err", ":=", "p", ".", "state", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "{", "return", "state", ".", "ISR", ",", "nil", "\n", "}", "\n", "}" ]
// ISR returns the broker IDs of the current in-sync replica set for the partition
[ "ISR", "returns", "the", "broker", "IDs", "of", "the", "current", "in", "-", "sync", "replica", "set", "for", "the", "partition" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L333-L339
10,675
wvanbergen/kazoo-go
topic_metadata.go
state
func (p *Partition) state() (partitionState, error) { var state partitionState node := fmt.Sprintf("%s/brokers/topics/%s/partitions/%d/state", p.topic.kz.conf.Chroot, p.topic.Name, p.ID) value, _, err := p.topic.kz.conn.Get(node) if err != nil { return state, err } if err := json.Unmarshal(value, &state); err != nil { return state, err } return state, nil }
go
func (p *Partition) state() (partitionState, error) { var state partitionState node := fmt.Sprintf("%s/brokers/topics/%s/partitions/%d/state", p.topic.kz.conf.Chroot, p.topic.Name, p.ID) value, _, err := p.topic.kz.conn.Get(node) if err != nil { return state, err } if err := json.Unmarshal(value, &state); err != nil { return state, err } return state, nil }
[ "func", "(", "p", "*", "Partition", ")", "state", "(", ")", "(", "partitionState", ",", "error", ")", "{", "var", "state", "partitionState", "\n", "node", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "topic", ".", "kz", ".", "conf", ".", "Chroot", ",", "p", ".", "topic", ".", "Name", ",", "p", ".", "ID", ")", "\n", "value", ",", "_", ",", "err", ":=", "p", ".", "topic", ".", "kz", ".", "conn", ".", "Get", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "state", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "value", ",", "&", "state", ")", ";", "err", "!=", "nil", "{", "return", "state", ",", "err", "\n", "}", "\n\n", "return", "state", ",", "nil", "\n", "}" ]
// state retrieves and parses the partition State
[ "state", "retrieves", "and", "parses", "the", "partition", "State" ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L365-L378
10,676
wvanbergen/kazoo-go
topic_metadata.go
Find
func (tl TopicList) Find(name string) *Topic { for _, topic := range tl { if topic.Name == name { return topic } } return nil }
go
func (tl TopicList) Find(name string) *Topic { for _, topic := range tl { if topic.Name == name { return topic } } return nil }
[ "func", "(", "tl", "TopicList", ")", "Find", "(", "name", "string", ")", "*", "Topic", "{", "for", "_", ",", "topic", ":=", "range", "tl", "{", "if", "topic", ".", "Name", "==", "name", "{", "return", "topic", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Find returns the topic with the given name if it exists in the topic list, // and will return `nil` otherwise.
[ "Find", "returns", "the", "topic", "with", "the", "given", "name", "if", "it", "exists", "in", "the", "topic", "list", "and", "will", "return", "nil", "otherwise", "." ]
f72d8611297a7cf105da904c04198ad701a60101
https://github.com/wvanbergen/kazoo-go/blob/f72d8611297a7cf105da904c04198ad701a60101/topic_metadata.go#L382-L389
10,677
go-chef/chef
reader.go
JSONReader
func JSONReader(v interface{}) (r io.Reader, err error) { buf := new(bytes.Buffer) err = json.NewEncoder(buf).Encode(v) r = bytes.NewReader(buf.Bytes()) return }
go
func JSONReader(v interface{}) (r io.Reader, err error) { buf := new(bytes.Buffer) err = json.NewEncoder(buf).Encode(v) r = bytes.NewReader(buf.Bytes()) return }
[ "func", "JSONReader", "(", "v", "interface", "{", "}", ")", "(", "r", "io", ".", "Reader", ",", "err", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "err", "=", "json", ".", "NewEncoder", "(", "buf", ")", ".", "Encode", "(", "v", ")", "\n", "r", "=", "bytes", ".", "NewReader", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "return", "\n", "}" ]
// JSONReader handles arbitrary types and synthesizes a streaming encoder for them.
[ "JSONReader", "handles", "arbitrary", "types", "and", "synthesizes", "a", "streaming", "encoder", "for", "them", "." ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/reader.go#L10-L15
10,678
go-chef/chef
authentication.go
privateEncrypt
func privateEncrypt(key *rsa.PrivateKey, data []byte) (enc []byte, err error) { k := (key.N.BitLen() + 7) / 8 tLen := len(data) // rfc2313, section 8: // The length of the data D shall not be more than k-11 octets if tLen > k-11 { err = errors.New("Data too long") return } em := make([]byte, k) em[1] = 1 for i := 2; i < k-tLen-1; i++ { em[i] = 0xff } copy(em[k-tLen:k], data) c := new(big.Int).SetBytes(em) if c.Cmp(key.N) > 0 { err = nil return } var m *big.Int var ir *big.Int if key.Precomputed.Dp == nil { m = new(big.Int).Exp(c, key.D, key.N) } else { // We have the precalculated values needed for the CRT. m = new(big.Int).Exp(c, key.Precomputed.Dp, key.Primes[0]) m2 := new(big.Int).Exp(c, key.Precomputed.Dq, key.Primes[1]) m.Sub(m, m2) if m.Sign() < 0 { m.Add(m, key.Primes[0]) } m.Mul(m, key.Precomputed.Qinv) m.Mod(m, key.Primes[0]) m.Mul(m, key.Primes[1]) m.Add(m, m2) for i, values := range key.Precomputed.CRTValues { prime := key.Primes[2+i] m2.Exp(c, values.Exp, prime) m2.Sub(m2, m) m2.Mul(m2, values.Coeff) m2.Mod(m2, prime) if m2.Sign() < 0 { m2.Add(m2, prime) } m2.Mul(m2, values.R) m.Add(m, m2) } } if ir != nil { // Unblind. m.Mul(m, ir) m.Mod(m, key.N) } enc = m.Bytes() return }
go
func privateEncrypt(key *rsa.PrivateKey, data []byte) (enc []byte, err error) { k := (key.N.BitLen() + 7) / 8 tLen := len(data) // rfc2313, section 8: // The length of the data D shall not be more than k-11 octets if tLen > k-11 { err = errors.New("Data too long") return } em := make([]byte, k) em[1] = 1 for i := 2; i < k-tLen-1; i++ { em[i] = 0xff } copy(em[k-tLen:k], data) c := new(big.Int).SetBytes(em) if c.Cmp(key.N) > 0 { err = nil return } var m *big.Int var ir *big.Int if key.Precomputed.Dp == nil { m = new(big.Int).Exp(c, key.D, key.N) } else { // We have the precalculated values needed for the CRT. m = new(big.Int).Exp(c, key.Precomputed.Dp, key.Primes[0]) m2 := new(big.Int).Exp(c, key.Precomputed.Dq, key.Primes[1]) m.Sub(m, m2) if m.Sign() < 0 { m.Add(m, key.Primes[0]) } m.Mul(m, key.Precomputed.Qinv) m.Mod(m, key.Primes[0]) m.Mul(m, key.Primes[1]) m.Add(m, m2) for i, values := range key.Precomputed.CRTValues { prime := key.Primes[2+i] m2.Exp(c, values.Exp, prime) m2.Sub(m2, m) m2.Mul(m2, values.Coeff) m2.Mod(m2, prime) if m2.Sign() < 0 { m2.Add(m2, prime) } m2.Mul(m2, values.R) m.Add(m, m2) } } if ir != nil { // Unblind. m.Mul(m, ir) m.Mod(m, key.N) } enc = m.Bytes() return }
[ "func", "privateEncrypt", "(", "key", "*", "rsa", ".", "PrivateKey", ",", "data", "[", "]", "byte", ")", "(", "enc", "[", "]", "byte", ",", "err", "error", ")", "{", "k", ":=", "(", "key", ".", "N", ".", "BitLen", "(", ")", "+", "7", ")", "/", "8", "\n", "tLen", ":=", "len", "(", "data", ")", "\n\n", "// rfc2313, section 8:", "// The length of the data D shall not be more than k-11 octets", "if", "tLen", ">", "k", "-", "11", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "em", ":=", "make", "(", "[", "]", "byte", ",", "k", ")", "\n", "em", "[", "1", "]", "=", "1", "\n", "for", "i", ":=", "2", ";", "i", "<", "k", "-", "tLen", "-", "1", ";", "i", "++", "{", "em", "[", "i", "]", "=", "0xff", "\n", "}", "\n", "copy", "(", "em", "[", "k", "-", "tLen", ":", "k", "]", ",", "data", ")", "\n", "c", ":=", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "em", ")", "\n", "if", "c", ".", "Cmp", "(", "key", ".", "N", ")", ">", "0", "{", "err", "=", "nil", "\n", "return", "\n", "}", "\n", "var", "m", "*", "big", ".", "Int", "\n", "var", "ir", "*", "big", ".", "Int", "\n", "if", "key", ".", "Precomputed", ".", "Dp", "==", "nil", "{", "m", "=", "new", "(", "big", ".", "Int", ")", ".", "Exp", "(", "c", ",", "key", ".", "D", ",", "key", ".", "N", ")", "\n", "}", "else", "{", "// We have the precalculated values needed for the CRT.", "m", "=", "new", "(", "big", ".", "Int", ")", ".", "Exp", "(", "c", ",", "key", ".", "Precomputed", ".", "Dp", ",", "key", ".", "Primes", "[", "0", "]", ")", "\n", "m2", ":=", "new", "(", "big", ".", "Int", ")", ".", "Exp", "(", "c", ",", "key", ".", "Precomputed", ".", "Dq", ",", "key", ".", "Primes", "[", "1", "]", ")", "\n", "m", ".", "Sub", "(", "m", ",", "m2", ")", "\n", "if", "m", ".", "Sign", "(", ")", "<", "0", "{", "m", ".", "Add", "(", "m", ",", "key", ".", "Primes", "[", "0", "]", ")", "\n", "}", "\n", "m", ".", "Mul", "(", "m", ",", "key", ".", "Precomputed", ".", "Qinv", ")", "\n", "m", ".", "Mod", "(", "m", ",", "key", ".", "Primes", "[", "0", "]", ")", "\n", "m", ".", "Mul", "(", "m", ",", "key", ".", "Primes", "[", "1", "]", ")", "\n", "m", ".", "Add", "(", "m", ",", "m2", ")", "\n\n", "for", "i", ",", "values", ":=", "range", "key", ".", "Precomputed", ".", "CRTValues", "{", "prime", ":=", "key", ".", "Primes", "[", "2", "+", "i", "]", "\n", "m2", ".", "Exp", "(", "c", ",", "values", ".", "Exp", ",", "prime", ")", "\n", "m2", ".", "Sub", "(", "m2", ",", "m", ")", "\n", "m2", ".", "Mul", "(", "m2", ",", "values", ".", "Coeff", ")", "\n", "m2", ".", "Mod", "(", "m2", ",", "prime", ")", "\n", "if", "m2", ".", "Sign", "(", ")", "<", "0", "{", "m2", ".", "Add", "(", "m2", ",", "prime", ")", "\n", "}", "\n", "m2", ".", "Mul", "(", "m2", ",", "values", ".", "R", ")", "\n", "m", ".", "Add", "(", "m", ",", "m2", ")", "\n", "}", "\n", "}", "\n\n", "if", "ir", "!=", "nil", "{", "// Unblind.", "m", ".", "Mul", "(", "m", ",", "ir", ")", "\n", "m", ".", "Mod", "(", "m", ",", "key", ".", "N", ")", "\n", "}", "\n", "enc", "=", "m", ".", "Bytes", "(", ")", "\n", "return", "\n", "}" ]
// privateEncrypt implements OpenSSL's RSA_private_encrypt function
[ "privateEncrypt", "implements", "OpenSSL", "s", "RSA_private_encrypt", "function" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/authentication.go#L23-L82
10,679
go-chef/chef
authentication.go
HashStr
func HashStr(toHash string) string { h := sha1.New() io.WriteString(h, toHash) hashed := base64.StdEncoding.EncodeToString(h.Sum(nil)) return hashed }
go
func HashStr(toHash string) string { h := sha1.New() io.WriteString(h, toHash) hashed := base64.StdEncoding.EncodeToString(h.Sum(nil)) return hashed }
[ "func", "HashStr", "(", "toHash", "string", ")", "string", "{", "h", ":=", "sha1", ".", "New", "(", ")", "\n", "io", ".", "WriteString", "(", "h", ",", "toHash", ")", "\n", "hashed", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "h", ".", "Sum", "(", "nil", ")", ")", "\n", "return", "hashed", "\n", "}" ]
// HashStr returns the base64 encoded SHA1 sum of the toHash string
[ "HashStr", "returns", "the", "base64", "encoded", "SHA1", "sum", "of", "the", "toHash", "string" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/authentication.go#L85-L90
10,680
go-chef/chef
authentication.go
Base64BlockEncode
func Base64BlockEncode(content []byte, limit int) []string { resultString := base64.StdEncoding.EncodeToString(content) var resultSlice []string index := 0 var maxLengthPerSlice int // No limit if limit == 0 { maxLengthPerSlice = len(resultString) } else { maxLengthPerSlice = limit } // Iterate through the encoded string storing // a max of <limit> per slice item for i := 0; i < len(resultString)/maxLengthPerSlice; i++ { resultSlice = append(resultSlice, resultString[index:index+maxLengthPerSlice]) index += maxLengthPerSlice } // Add remaining chunk to the end of the slice if len(resultString)%maxLengthPerSlice != 0 { resultSlice = append(resultSlice, resultString[index:]) } return resultSlice }
go
func Base64BlockEncode(content []byte, limit int) []string { resultString := base64.StdEncoding.EncodeToString(content) var resultSlice []string index := 0 var maxLengthPerSlice int // No limit if limit == 0 { maxLengthPerSlice = len(resultString) } else { maxLengthPerSlice = limit } // Iterate through the encoded string storing // a max of <limit> per slice item for i := 0; i < len(resultString)/maxLengthPerSlice; i++ { resultSlice = append(resultSlice, resultString[index:index+maxLengthPerSlice]) index += maxLengthPerSlice } // Add remaining chunk to the end of the slice if len(resultString)%maxLengthPerSlice != 0 { resultSlice = append(resultSlice, resultString[index:]) } return resultSlice }
[ "func", "Base64BlockEncode", "(", "content", "[", "]", "byte", ",", "limit", "int", ")", "[", "]", "string", "{", "resultString", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "content", ")", "\n", "var", "resultSlice", "[", "]", "string", "\n\n", "index", ":=", "0", "\n\n", "var", "maxLengthPerSlice", "int", "\n\n", "// No limit", "if", "limit", "==", "0", "{", "maxLengthPerSlice", "=", "len", "(", "resultString", ")", "\n", "}", "else", "{", "maxLengthPerSlice", "=", "limit", "\n", "}", "\n\n", "// Iterate through the encoded string storing", "// a max of <limit> per slice item", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "resultString", ")", "/", "maxLengthPerSlice", ";", "i", "++", "{", "resultSlice", "=", "append", "(", "resultSlice", ",", "resultString", "[", "index", ":", "index", "+", "maxLengthPerSlice", "]", ")", "\n", "index", "+=", "maxLengthPerSlice", "\n", "}", "\n\n", "// Add remaining chunk to the end of the slice", "if", "len", "(", "resultString", ")", "%", "maxLengthPerSlice", "!=", "0", "{", "resultSlice", "=", "append", "(", "resultSlice", ",", "resultString", "[", "index", ":", "]", ")", "\n", "}", "\n\n", "return", "resultSlice", "\n", "}" ]
// Base64BlockEncode takes a byte slice and breaks it up into a // slice of base64 encoded strings
[ "Base64BlockEncode", "takes", "a", "byte", "slice", "and", "breaks", "it", "up", "into", "a", "slice", "of", "base64", "encoded", "strings" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/authentication.go#L94-L122
10,681
go-chef/chef
examples/sandboxes/sandboxes.go
random_data
func random_data(size int) (b []byte) { b = make([]byte, size) rand.Read(b) return }
go
func random_data(size int) (b []byte) { b = make([]byte, size) rand.Read(b) return }
[ "func", "random_data", "(", "size", "int", ")", "(", "b", "[", "]", "byte", ")", "{", "b", "=", "make", "(", "[", "]", "byte", ",", "size", ")", "\n", "rand", ".", "Read", "(", "b", ")", "\n", "return", "\n", "}" ]
//random_data makes random byte slice for building junk sandbox data
[ "random_data", "makes", "random", "byte", "slice", "for", "building", "junk", "sandbox", "data" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/examples/sandboxes/sandboxes.go#L18-L22
10,682
go-chef/chef
client.go
String
func (c ApiClientListResult) String() (out string) { for k, v := range c { out += fmt.Sprintf("%s => %s\n", k, v) } return out }
go
func (c ApiClientListResult) String() (out string) { for k, v := range c { out += fmt.Sprintf("%s => %s\n", k, v) } return out }
[ "func", "(", "c", "ApiClientListResult", ")", "String", "(", ")", "(", "out", "string", ")", "{", "for", "k", ",", "v", ":=", "range", "c", "{", "out", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// String makes ApiClientListResult implement the string result
[ "String", "makes", "ApiClientListResult", "implement", "the", "string", "result" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/client.go#L50-L55
10,683
go-chef/chef
node.go
NewNode
func NewNode(name string) (node Node) { node = Node{ Name: name, Environment: "_default", ChefType: "node", JsonClass: "Chef::Node", } return }
go
func NewNode(name string) (node Node) { node = Node{ Name: name, Environment: "_default", ChefType: "node", JsonClass: "Chef::Node", } return }
[ "func", "NewNode", "(", "name", "string", ")", "(", "node", "Node", ")", "{", "node", "=", "Node", "{", "Name", ":", "name", ",", "Environment", ":", "\"", "\"", ",", "ChefType", ":", "\"", "\"", ",", "JsonClass", ":", "\"", "\"", ",", "}", "\n", "return", "\n", "}" ]
// NewNode is the Node constructor method
[ "NewNode", "is", "the", "Node", "constructor", "method" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/node.go#L29-L37
10,684
go-chef/chef
http.go
Buffer
func (body *Body) Buffer() *bytes.Buffer { var b bytes.Buffer if body.Reader == nil { return &b } b.ReadFrom(body.Reader) _, err := body.Reader.(io.Seeker).Seek(0, 0) if err != nil { log.Fatal(err) } return &b }
go
func (body *Body) Buffer() *bytes.Buffer { var b bytes.Buffer if body.Reader == nil { return &b } b.ReadFrom(body.Reader) _, err := body.Reader.(io.Seeker).Seek(0, 0) if err != nil { log.Fatal(err) } return &b }
[ "func", "(", "body", "*", "Body", ")", "Buffer", "(", ")", "*", "bytes", ".", "Buffer", "{", "var", "b", "bytes", ".", "Buffer", "\n", "if", "body", ".", "Reader", "==", "nil", "{", "return", "&", "b", "\n", "}", "\n\n", "b", ".", "ReadFrom", "(", "body", ".", "Reader", ")", "\n", "_", ",", "err", ":=", "body", ".", "Reader", ".", "(", "io", ".", "Seeker", ")", ".", "Seek", "(", "0", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "return", "&", "b", "\n", "}" ]
// Buffer creates a byte.Buffer copy from a io.Reader resets read on reader to 0,0
[ "Buffer", "creates", "a", "byte", ".", "Buffer", "copy", "from", "a", "io", ".", "Reader", "resets", "read", "on", "reader", "to", "0", "0" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/http.go#L82-L94
10,685
go-chef/chef
http.go
Hash
func (body *Body) Hash() (h string) { b := body.Buffer() // empty buffs should return a empty string if b.Len() == 0 { h = HashStr("") } h = HashStr(b.String()) return }
go
func (body *Body) Hash() (h string) { b := body.Buffer() // empty buffs should return a empty string if b.Len() == 0 { h = HashStr("") } h = HashStr(b.String()) return }
[ "func", "(", "body", "*", "Body", ")", "Hash", "(", ")", "(", "h", "string", ")", "{", "b", ":=", "body", ".", "Buffer", "(", ")", "\n", "// empty buffs should return a empty string", "if", "b", ".", "Len", "(", ")", "==", "0", "{", "h", "=", "HashStr", "(", "\"", "\"", ")", "\n", "}", "\n", "h", "=", "HashStr", "(", "b", ".", "String", "(", ")", ")", "\n", "return", "\n", "}" ]
// Hash calculates the body content hash
[ "Hash", "calculates", "the", "body", "content", "hash" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/http.go#L97-L105
10,686
go-chef/chef
http.go
NewClient
func NewClient(cfg *Config) (*Client, error) { pk, err := PrivateKeyFromString([]byte(cfg.Key)) if err != nil { return nil, err } baseUrl, _ := url.Parse(cfg.BaseURL) tr := &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSClientConfig: &tls.Config{InsecureSkipVerify: cfg.SkipSSL}, TLSHandshakeTimeout: 10 * time.Second, } c := &Client{ Auth: &AuthConfig{ PrivateKey: pk, ClientName: cfg.Name, }, client: &http.Client{ Transport: tr, Timeout: cfg.Timeout * time.Second, }, BaseURL: baseUrl, } c.ACLs = &ACLService{client: c} c.Clients = &ApiClientService{client: c} c.Cookbooks = &CookbookService{client: c} c.DataBags = &DataBagService{client: c} c.Environments = &EnvironmentService{client: c} c.Nodes = &NodeService{client: c} c.Principals = &PrincipalService{client: c} c.Roles = &RoleService{client: c} c.Sandboxes = &SandboxService{client: c} c.Search = &SearchService{client: c} return c, nil }
go
func NewClient(cfg *Config) (*Client, error) { pk, err := PrivateKeyFromString([]byte(cfg.Key)) if err != nil { return nil, err } baseUrl, _ := url.Parse(cfg.BaseURL) tr := &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSClientConfig: &tls.Config{InsecureSkipVerify: cfg.SkipSSL}, TLSHandshakeTimeout: 10 * time.Second, } c := &Client{ Auth: &AuthConfig{ PrivateKey: pk, ClientName: cfg.Name, }, client: &http.Client{ Transport: tr, Timeout: cfg.Timeout * time.Second, }, BaseURL: baseUrl, } c.ACLs = &ACLService{client: c} c.Clients = &ApiClientService{client: c} c.Cookbooks = &CookbookService{client: c} c.DataBags = &DataBagService{client: c} c.Environments = &EnvironmentService{client: c} c.Nodes = &NodeService{client: c} c.Principals = &PrincipalService{client: c} c.Roles = &RoleService{client: c} c.Sandboxes = &SandboxService{client: c} c.Search = &SearchService{client: c} return c, nil }
[ "func", "NewClient", "(", "cfg", "*", "Config", ")", "(", "*", "Client", ",", "error", ")", "{", "pk", ",", "err", ":=", "PrivateKeyFromString", "(", "[", "]", "byte", "(", "cfg", ".", "Key", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "baseUrl", ",", "_", ":=", "url", ".", "Parse", "(", "cfg", ".", "BaseURL", ")", "\n\n", "tr", ":=", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "Dial", ":", "(", "&", "net", ".", "Dialer", "{", "Timeout", ":", "30", "*", "time", ".", "Second", ",", "KeepAlive", ":", "30", "*", "time", ".", "Second", ",", "}", ")", ".", "Dial", ",", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "cfg", ".", "SkipSSL", "}", ",", "TLSHandshakeTimeout", ":", "10", "*", "time", ".", "Second", ",", "}", "\n\n", "c", ":=", "&", "Client", "{", "Auth", ":", "&", "AuthConfig", "{", "PrivateKey", ":", "pk", ",", "ClientName", ":", "cfg", ".", "Name", ",", "}", ",", "client", ":", "&", "http", ".", "Client", "{", "Transport", ":", "tr", ",", "Timeout", ":", "cfg", ".", "Timeout", "*", "time", ".", "Second", ",", "}", ",", "BaseURL", ":", "baseUrl", ",", "}", "\n", "c", ".", "ACLs", "=", "&", "ACLService", "{", "client", ":", "c", "}", "\n", "c", ".", "Clients", "=", "&", "ApiClientService", "{", "client", ":", "c", "}", "\n", "c", ".", "Cookbooks", "=", "&", "CookbookService", "{", "client", ":", "c", "}", "\n", "c", ".", "DataBags", "=", "&", "DataBagService", "{", "client", ":", "c", "}", "\n", "c", ".", "Environments", "=", "&", "EnvironmentService", "{", "client", ":", "c", "}", "\n", "c", ".", "Nodes", "=", "&", "NodeService", "{", "client", ":", "c", "}", "\n", "c", ".", "Principals", "=", "&", "PrincipalService", "{", "client", ":", "c", "}", "\n", "c", ".", "Roles", "=", "&", "RoleService", "{", "client", ":", "c", "}", "\n", "c", ".", "Sandboxes", "=", "&", "SandboxService", "{", "client", ":", "c", "}", "\n", "c", ".", "Search", "=", "&", "SearchService", "{", "client", ":", "c", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// NewClient is the client generator used to instantiate a client for talking to a chef-server // It is a simple constructor for the Client struct intended as a easy interface for issuing // signed requests
[ "NewClient", "is", "the", "client", "generator", "used", "to", "instantiate", "a", "client", "for", "talking", "to", "a", "chef", "-", "server", "It", "is", "a", "simple", "constructor", "for", "the", "Client", "struct", "intended", "as", "a", "easy", "interface", "for", "issuing", "signed", "requests" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/http.go#L124-L164
10,687
go-chef/chef
http.go
magicRequestDecoder
func (c *Client) magicRequestDecoder(method, path string, body io.Reader, v interface{}) error { req, err := c.NewRequest(method, path, body) if err != nil { return err } debug("Request: %+v \n", req) res, err := c.Do(req, v) if res != nil { defer res.Body.Close() } debug("Response: %+v \n", res) if err != nil { return err } return err }
go
func (c *Client) magicRequestDecoder(method, path string, body io.Reader, v interface{}) error { req, err := c.NewRequest(method, path, body) if err != nil { return err } debug("Request: %+v \n", req) res, err := c.Do(req, v) if res != nil { defer res.Body.Close() } debug("Response: %+v \n", res) if err != nil { return err } return err }
[ "func", "(", "c", "*", "Client", ")", "magicRequestDecoder", "(", "method", ",", "path", "string", ",", "body", "io", ".", "Reader", ",", "v", "interface", "{", "}", ")", "error", "{", "req", ",", "err", ":=", "c", ".", "NewRequest", "(", "method", ",", "path", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "debug", "(", "\"", "\\n", "\"", ",", "req", ")", "\n", "res", ",", "err", ":=", "c", ".", "Do", "(", "req", ",", "v", ")", "\n", "if", "res", "!=", "nil", "{", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "debug", "(", "\"", "\\n", "\"", ",", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "err", "\n", "}" ]
// magicRequestDecoder performs a request on an endpoint, and decodes the response into the passed in Type
[ "magicRequestDecoder", "performs", "a", "request", "on", "an", "endpoint", "and", "decodes", "the", "response", "into", "the", "passed", "in", "Type" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/http.go#L167-L183
10,688
go-chef/chef
http.go
NewRequest
func (c *Client) NewRequest(method string, requestUrl string, body io.Reader) (*http.Request, error) { relativeUrl, err := url.Parse(requestUrl) if err != nil { return nil, err } u := c.BaseURL.ResolveReference(relativeUrl) // NewRequest uses a new value object of body req, err := http.NewRequest(method, u.String(), body) if err != nil { return nil, err } // parse and encode Querystring Values values := req.URL.Query() req.URL.RawQuery = values.Encode() debug("Encoded url %+v", u) myBody := &Body{body} if body != nil { // Detect Content-type req.Header.Set("Content-Type", myBody.ContentType()) } // Calculate the body hash req.Header.Set("X-Ops-Content-Hash", myBody.Hash()) // don't have to check this works, signRequest only emits error when signing hash is not valid, and we baked that in c.Auth.SignRequest(req) return req, nil }
go
func (c *Client) NewRequest(method string, requestUrl string, body io.Reader) (*http.Request, error) { relativeUrl, err := url.Parse(requestUrl) if err != nil { return nil, err } u := c.BaseURL.ResolveReference(relativeUrl) // NewRequest uses a new value object of body req, err := http.NewRequest(method, u.String(), body) if err != nil { return nil, err } // parse and encode Querystring Values values := req.URL.Query() req.URL.RawQuery = values.Encode() debug("Encoded url %+v", u) myBody := &Body{body} if body != nil { // Detect Content-type req.Header.Set("Content-Type", myBody.ContentType()) } // Calculate the body hash req.Header.Set("X-Ops-Content-Hash", myBody.Hash()) // don't have to check this works, signRequest only emits error when signing hash is not valid, and we baked that in c.Auth.SignRequest(req) return req, nil }
[ "func", "(", "c", "*", "Client", ")", "NewRequest", "(", "method", "string", ",", "requestUrl", "string", ",", "body", "io", ".", "Reader", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "relativeUrl", ",", "err", ":=", "url", ".", "Parse", "(", "requestUrl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "u", ":=", "c", ".", "BaseURL", ".", "ResolveReference", "(", "relativeUrl", ")", "\n\n", "// NewRequest uses a new value object of body", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "u", ".", "String", "(", ")", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// parse and encode Querystring Values", "values", ":=", "req", ".", "URL", ".", "Query", "(", ")", "\n", "req", ".", "URL", ".", "RawQuery", "=", "values", ".", "Encode", "(", ")", "\n", "debug", "(", "\"", "\"", ",", "u", ")", "\n\n", "myBody", ":=", "&", "Body", "{", "body", "}", "\n\n", "if", "body", "!=", "nil", "{", "// Detect Content-type", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "myBody", ".", "ContentType", "(", ")", ")", "\n", "}", "\n\n", "// Calculate the body hash", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "myBody", ".", "Hash", "(", ")", ")", "\n\n", "// don't have to check this works, signRequest only emits error when signing hash is not valid, and we baked that in", "c", ".", "Auth", ".", "SignRequest", "(", "req", ")", "\n", "return", "req", ",", "nil", "\n", "}" ]
// NewRequest returns a signed request suitable for the chef server
[ "NewRequest", "returns", "a", "signed", "request", "suitable", "for", "the", "chef", "server" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/http.go#L186-L217
10,689
go-chef/chef
http.go
CheckResponse
func CheckResponse(r *http.Response) error { if c := r.StatusCode; 200 <= c && c <= 299 { return nil } errorResponse := &ErrorResponse{Response: r} data, err := ioutil.ReadAll(r.Body) if err == nil && data != nil { json.Unmarshal(data, errorResponse) } return errorResponse }
go
func CheckResponse(r *http.Response) error { if c := r.StatusCode; 200 <= c && c <= 299 { return nil } errorResponse := &ErrorResponse{Response: r} data, err := ioutil.ReadAll(r.Body) if err == nil && data != nil { json.Unmarshal(data, errorResponse) } return errorResponse }
[ "func", "CheckResponse", "(", "r", "*", "http", ".", "Response", ")", "error", "{", "if", "c", ":=", "r", ".", "StatusCode", ";", "200", "<=", "c", "&&", "c", "<=", "299", "{", "return", "nil", "\n", "}", "\n", "errorResponse", ":=", "&", "ErrorResponse", "{", "Response", ":", "r", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "if", "err", "==", "nil", "&&", "data", "!=", "nil", "{", "json", ".", "Unmarshal", "(", "data", ",", "errorResponse", ")", "\n", "}", "\n", "return", "errorResponse", "\n", "}" ]
// CheckResponse receives a pointer to a http.Response and generates an Error via unmarshalling
[ "CheckResponse", "receives", "a", "pointer", "to", "a", "http", ".", "Response", "and", "generates", "an", "Error", "via", "unmarshalling" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/http.go#L220-L230
10,690
go-chef/chef
http.go
Do
func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error) { res, err := c.client.Do(req) if err != nil { return nil, err } // BUG(fujin) tightly coupled err = CheckResponse(res) // <-- if err != nil { return res, err } if v != nil { if w, ok := v.(io.Writer); ok { io.Copy(w, res.Body) } else { err = json.NewDecoder(res.Body).Decode(v) if err != nil { return res, err } } } return res, nil }
go
func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error) { res, err := c.client.Do(req) if err != nil { return nil, err } // BUG(fujin) tightly coupled err = CheckResponse(res) // <-- if err != nil { return res, err } if v != nil { if w, ok := v.(io.Writer); ok { io.Copy(w, res.Body) } else { err = json.NewDecoder(res.Body).Decode(v) if err != nil { return res, err } } } return res, nil }
[ "func", "(", "c", "*", "Client", ")", "Do", "(", "req", "*", "http", ".", "Request", ",", "v", "interface", "{", "}", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "res", ",", "err", ":=", "c", ".", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// BUG(fujin) tightly coupled", "err", "=", "CheckResponse", "(", "res", ")", "// <--", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n\n", "if", "v", "!=", "nil", "{", "if", "w", ",", "ok", ":=", "v", ".", "(", "io", ".", "Writer", ")", ";", "ok", "{", "io", ".", "Copy", "(", "w", ",", "res", ".", "Body", ")", "\n", "}", "else", "{", "err", "=", "json", ".", "NewDecoder", "(", "res", ".", "Body", ")", ".", "Decode", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// Do is used either internally via our magic request shite or a user may use it
[ "Do", "is", "used", "either", "internally", "via", "our", "magic", "request", "shite", "or", "a", "user", "may", "use", "it" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/http.go#L233-L256
10,691
go-chef/chef
http.go
SignRequest
func (ac AuthConfig) SignRequest(request *http.Request) error { // sanitize the path for the chef-server // chef-server doesn't support '//' in the Hash Path. var endpoint string if request.URL.Path != "" { endpoint = path.Clean(request.URL.Path) request.URL.Path = endpoint } else { endpoint = request.URL.Path } vals := map[string]string{ "Method": request.Method, "Hashed Path": HashStr(endpoint), "Accept": "application/json", "X-Chef-Version": ChefVersion, "X-Ops-Timestamp": time.Now().UTC().Format(time.RFC3339), "X-Ops-UserId": ac.ClientName, "X-Ops-Sign": "algorithm=sha1;version=1.0", "X-Ops-Content-Hash": request.Header.Get("X-Ops-Content-Hash"), } for _, key := range []string{"Method", "Accept", "X-Chef-Version", "X-Ops-Timestamp", "X-Ops-UserId", "X-Ops-Sign"} { request.Header.Set(key, vals[key]) } // To validate the signature it seems to be very particular var content string for _, key := range []string{"Method", "Hashed Path", "X-Ops-Content-Hash", "X-Ops-Timestamp", "X-Ops-UserId"} { content += fmt.Sprintf("%s:%s\n", key, vals[key]) } content = strings.TrimSuffix(content, "\n") // generate signed string of headers // Since we've gone through additional validation steps above, // we shouldn't get an error at this point signature, err := GenerateSignature(ac.PrivateKey, content) if err != nil { return err } // TODO: THIS IS CHEF PROTOCOL SPECIFIC // Signature is made up of n 60 length chunks base64sig := Base64BlockEncode(signature, 60) // roll over the auth slice and add the apropriate header for index, value := range base64sig { request.Header.Set(fmt.Sprintf("X-Ops-Authorization-%d", index+1), string(value)) } return nil }
go
func (ac AuthConfig) SignRequest(request *http.Request) error { // sanitize the path for the chef-server // chef-server doesn't support '//' in the Hash Path. var endpoint string if request.URL.Path != "" { endpoint = path.Clean(request.URL.Path) request.URL.Path = endpoint } else { endpoint = request.URL.Path } vals := map[string]string{ "Method": request.Method, "Hashed Path": HashStr(endpoint), "Accept": "application/json", "X-Chef-Version": ChefVersion, "X-Ops-Timestamp": time.Now().UTC().Format(time.RFC3339), "X-Ops-UserId": ac.ClientName, "X-Ops-Sign": "algorithm=sha1;version=1.0", "X-Ops-Content-Hash": request.Header.Get("X-Ops-Content-Hash"), } for _, key := range []string{"Method", "Accept", "X-Chef-Version", "X-Ops-Timestamp", "X-Ops-UserId", "X-Ops-Sign"} { request.Header.Set(key, vals[key]) } // To validate the signature it seems to be very particular var content string for _, key := range []string{"Method", "Hashed Path", "X-Ops-Content-Hash", "X-Ops-Timestamp", "X-Ops-UserId"} { content += fmt.Sprintf("%s:%s\n", key, vals[key]) } content = strings.TrimSuffix(content, "\n") // generate signed string of headers // Since we've gone through additional validation steps above, // we shouldn't get an error at this point signature, err := GenerateSignature(ac.PrivateKey, content) if err != nil { return err } // TODO: THIS IS CHEF PROTOCOL SPECIFIC // Signature is made up of n 60 length chunks base64sig := Base64BlockEncode(signature, 60) // roll over the auth slice and add the apropriate header for index, value := range base64sig { request.Header.Set(fmt.Sprintf("X-Ops-Authorization-%d", index+1), string(value)) } return nil }
[ "func", "(", "ac", "AuthConfig", ")", "SignRequest", "(", "request", "*", "http", ".", "Request", ")", "error", "{", "// sanitize the path for the chef-server", "// chef-server doesn't support '//' in the Hash Path.", "var", "endpoint", "string", "\n", "if", "request", ".", "URL", ".", "Path", "!=", "\"", "\"", "{", "endpoint", "=", "path", ".", "Clean", "(", "request", ".", "URL", ".", "Path", ")", "\n", "request", ".", "URL", ".", "Path", "=", "endpoint", "\n", "}", "else", "{", "endpoint", "=", "request", ".", "URL", ".", "Path", "\n", "}", "\n\n", "vals", ":=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "request", ".", "Method", ",", "\"", "\"", ":", "HashStr", "(", "endpoint", ")", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "ChefVersion", ",", "\"", "\"", ":", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Format", "(", "time", ".", "RFC3339", ")", ",", "\"", "\"", ":", "ac", ".", "ClientName", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "request", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "}", "\n\n", "for", "_", ",", "key", ":=", "range", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "{", "request", ".", "Header", ".", "Set", "(", "key", ",", "vals", "[", "key", "]", ")", "\n", "}", "\n\n", "// To validate the signature it seems to be very particular", "var", "content", "string", "\n", "for", "_", ",", "key", ":=", "range", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "{", "content", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "key", ",", "vals", "[", "key", "]", ")", "\n", "}", "\n", "content", "=", "strings", ".", "TrimSuffix", "(", "content", ",", "\"", "\\n", "\"", ")", "\n", "// generate signed string of headers", "// Since we've gone through additional validation steps above,", "// we shouldn't get an error at this point", "signature", ",", "err", ":=", "GenerateSignature", "(", "ac", ".", "PrivateKey", ",", "content", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// TODO: THIS IS CHEF PROTOCOL SPECIFIC", "// Signature is made up of n 60 length chunks", "base64sig", ":=", "Base64BlockEncode", "(", "signature", ",", "60", ")", "\n\n", "// roll over the auth slice and add the apropriate header", "for", "index", ",", "value", ":=", "range", "base64sig", "{", "request", ".", "Header", ".", "Set", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "index", "+", "1", ")", ",", "string", "(", "value", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SignRequest modifies headers of an http.Request
[ "SignRequest", "modifies", "headers", "of", "an", "http", ".", "Request" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/http.go#L259-L309
10,692
go-chef/chef
http.go
PrivateKeyFromString
func PrivateKeyFromString(key []byte) (*rsa.PrivateKey, error) { block, _ := pem.Decode(key) if block == nil { return nil, fmt.Errorf("private key block size invalid") } rsaKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, err } return rsaKey, nil }
go
func PrivateKeyFromString(key []byte) (*rsa.PrivateKey, error) { block, _ := pem.Decode(key) if block == nil { return nil, fmt.Errorf("private key block size invalid") } rsaKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, err } return rsaKey, nil }
[ "func", "PrivateKeyFromString", "(", "key", "[", "]", "byte", ")", "(", "*", "rsa", ".", "PrivateKey", ",", "error", ")", "{", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "key", ")", "\n", "if", "block", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "rsaKey", ",", "err", ":=", "x509", ".", "ParsePKCS1PrivateKey", "(", "block", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "rsaKey", ",", "nil", "\n", "}" ]
// PrivateKeyFromString parses an RSA private key from a string
[ "PrivateKeyFromString", "parses", "an", "RSA", "private", "key", "from", "a", "string" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/http.go#L312-L322
10,693
go-chef/chef
search.go
String
func (q SearchQuery) String() string { return fmt.Sprintf("%s?q=%s&rows=%d&sort=%s&start=%d", q.Index, q.Query, q.Rows, q.SortBy, q.Start) }
go
func (q SearchQuery) String() string { return fmt.Sprintf("%s?q=%s&rows=%d&sort=%s&start=%d", q.Index, q.Query, q.Rows, q.SortBy, q.Start) }
[ "func", "(", "q", "SearchQuery", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "q", ".", "Index", ",", "q", ".", "Query", ",", "q", ".", "Rows", ",", "q", ".", "SortBy", ",", "q", ".", "Start", ")", "\n", "}" ]
// String implements the Stringer Interface for the SearchQuery
[ "String", "implements", "the", "Stringer", "Interface", "for", "the", "SearchQuery" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/search.go#L32-L34
10,694
go-chef/chef
search.go
Do
func (q SearchQuery) Do(client *Client) (res SearchResult, err error) { fullUrl := fmt.Sprintf("search/%s", q) err = client.magicRequestDecoder("GET", fullUrl, nil, &res) return }
go
func (q SearchQuery) Do(client *Client) (res SearchResult, err error) { fullUrl := fmt.Sprintf("search/%s", q) err = client.magicRequestDecoder("GET", fullUrl, nil, &res) return }
[ "func", "(", "q", "SearchQuery", ")", "Do", "(", "client", "*", "Client", ")", "(", "res", "SearchResult", ",", "err", "error", ")", "{", "fullUrl", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "q", ")", "\n", "err", "=", "client", ".", "magicRequestDecoder", "(", "\"", "\"", ",", "fullUrl", ",", "nil", ",", "&", "res", ")", "\n", "return", "\n", "}" ]
// Do will execute the search query on the client
[ "Do", "will", "execute", "the", "search", "query", "on", "the", "client" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/search.go#L44-L48
10,695
go-chef/chef
search.go
DoPartial
func (q SearchQuery) DoPartial(client *Client, params map[string]interface{}) (res SearchResult, err error) { fullUrl := fmt.Sprintf("search/%s", q) body, err := JSONReader(params) if err != nil { debug("Problem encoding params for body", err.Error()) return } err = client.magicRequestDecoder("POST", fullUrl, body, &res) return }
go
func (q SearchQuery) DoPartial(client *Client, params map[string]interface{}) (res SearchResult, err error) { fullUrl := fmt.Sprintf("search/%s", q) body, err := JSONReader(params) if err != nil { debug("Problem encoding params for body", err.Error()) return } err = client.magicRequestDecoder("POST", fullUrl, body, &res) return }
[ "func", "(", "q", "SearchQuery", ")", "DoPartial", "(", "client", "*", "Client", ",", "params", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "res", "SearchResult", ",", "err", "error", ")", "{", "fullUrl", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "q", ")", "\n\n", "body", ",", "err", ":=", "JSONReader", "(", "params", ")", "\n", "if", "err", "!=", "nil", "{", "debug", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "err", "=", "client", ".", "magicRequestDecoder", "(", "\"", "\"", ",", "fullUrl", ",", "body", ",", "&", "res", ")", "\n", "return", "\n", "}" ]
// DoPartial will execute the search query on the client with partal mapping
[ "DoPartial", "will", "execute", "the", "search", "query", "on", "the", "client", "with", "partal", "mapping" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/search.go#L51-L62
10,696
go-chef/chef
search.go
NewQuery
func (e SearchService) NewQuery(idx, statement string) (query SearchQuery, err error) { // validate statement if !strings.Contains(statement, ":") { err = errors.New("statement is malformed") return } query = SearchQuery{ Index: idx, Query: statement, // These are the defaults in chef: https://github.com/opscode/chef/blob/master/lib/chef/search/query.rb#L102-L105 SortBy: "X_CHEF_id_CHEF_X asc", Start: 0, Rows: 1000, } return }
go
func (e SearchService) NewQuery(idx, statement string) (query SearchQuery, err error) { // validate statement if !strings.Contains(statement, ":") { err = errors.New("statement is malformed") return } query = SearchQuery{ Index: idx, Query: statement, // These are the defaults in chef: https://github.com/opscode/chef/blob/master/lib/chef/search/query.rb#L102-L105 SortBy: "X_CHEF_id_CHEF_X asc", Start: 0, Rows: 1000, } return }
[ "func", "(", "e", "SearchService", ")", "NewQuery", "(", "idx", ",", "statement", "string", ")", "(", "query", "SearchQuery", ",", "err", "error", ")", "{", "// validate statement", "if", "!", "strings", ".", "Contains", "(", "statement", ",", "\"", "\"", ")", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "query", "=", "SearchQuery", "{", "Index", ":", "idx", ",", "Query", ":", "statement", ",", "// These are the defaults in chef: https://github.com/opscode/chef/blob/master/lib/chef/search/query.rb#L102-L105", "SortBy", ":", "\"", "\"", ",", "Start", ":", "0", ",", "Rows", ":", "1000", ",", "}", "\n\n", "return", "\n", "}" ]
// NewSearch is a constructor for a SearchQuery struct. This is used by other search service methods to perform search requests on the server
[ "NewSearch", "is", "a", "constructor", "for", "a", "SearchQuery", "struct", ".", "This", "is", "used", "by", "other", "search", "service", "methods", "to", "perform", "search", "requests", "on", "the", "server" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/search.go#L65-L82
10,697
go-chef/chef
search.go
PartialExec
func (e SearchService) PartialExec(idx, statement string, params map[string]interface{}) (res SearchResult, err error) { query := SearchQuery{ Index: idx, Query: statement, // These are the defaults in chef: https://github.com/opscode/chef/blob/master/lib/chef/search/query.rb#L102-L105 SortBy: "X_CHEF_id_CHEF_X asc", Start: 0, Rows: 1000, } fullUrl := fmt.Sprintf("search/%s", query) body, err := JSONReader(params) if err != nil { debug("Problem encoding params for body") return } err = e.client.magicRequestDecoder("POST", fullUrl, body, &res) return }
go
func (e SearchService) PartialExec(idx, statement string, params map[string]interface{}) (res SearchResult, err error) { query := SearchQuery{ Index: idx, Query: statement, // These are the defaults in chef: https://github.com/opscode/chef/blob/master/lib/chef/search/query.rb#L102-L105 SortBy: "X_CHEF_id_CHEF_X asc", Start: 0, Rows: 1000, } fullUrl := fmt.Sprintf("search/%s", query) body, err := JSONReader(params) if err != nil { debug("Problem encoding params for body") return } err = e.client.magicRequestDecoder("POST", fullUrl, body, &res) return }
[ "func", "(", "e", "SearchService", ")", "PartialExec", "(", "idx", ",", "statement", "string", ",", "params", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "res", "SearchResult", ",", "err", "error", ")", "{", "query", ":=", "SearchQuery", "{", "Index", ":", "idx", ",", "Query", ":", "statement", ",", "// These are the defaults in chef: https://github.com/opscode/chef/blob/master/lib/chef/search/query.rb#L102-L105", "SortBy", ":", "\"", "\"", ",", "Start", ":", "0", ",", "Rows", ":", "1000", ",", "}", "\n\n", "fullUrl", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "query", ")", "\n\n", "body", ",", "err", ":=", "JSONReader", "(", "params", ")", "\n", "if", "err", "!=", "nil", "{", "debug", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "err", "=", "e", ".", "client", ".", "magicRequestDecoder", "(", "\"", "\"", ",", "fullUrl", ",", "body", ",", "&", "res", ")", "\n", "return", "\n", "}" ]
// PartialExec Executes a partial search based on passed in params and the query.
[ "PartialExec", "Executes", "a", "partial", "search", "based", "on", "passed", "in", "params", "and", "the", "query", "." ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/search.go#L120-L140
10,698
go-chef/chef
sandbox.go
Put
func (s SandboxService) Put(id string) (box Sandbox, err error) { answer := make(map[string]bool) answer["is_completed"] = true body, err := JSONReader(answer) if id == "" { return box, fmt.Errorf("must supply sandbox id to PUT request.") } err = s.client.magicRequestDecoder("PUT", "/sandboxes/"+id, body, &box) return }
go
func (s SandboxService) Put(id string) (box Sandbox, err error) { answer := make(map[string]bool) answer["is_completed"] = true body, err := JSONReader(answer) if id == "" { return box, fmt.Errorf("must supply sandbox id to PUT request.") } err = s.client.magicRequestDecoder("PUT", "/sandboxes/"+id, body, &box) return }
[ "func", "(", "s", "SandboxService", ")", "Put", "(", "id", "string", ")", "(", "box", "Sandbox", ",", "err", "error", ")", "{", "answer", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "answer", "[", "\"", "\"", "]", "=", "true", "\n", "body", ",", "err", ":=", "JSONReader", "(", "answer", ")", "\n\n", "if", "id", "==", "\"", "\"", "{", "return", "box", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "err", "=", "s", ".", "client", ".", "magicRequestDecoder", "(", "\"", "\"", ",", "\"", "\"", "+", "id", ",", "body", ",", "&", "box", ")", "\n", "return", "\n", "}" ]
// Put is used to commit a sandbox ID to the chef server. To singal that the sandox you have Posted is now uploaded.
[ "Put", "is", "used", "to", "commit", "a", "sandbox", "ID", "to", "the", "chef", "server", ".", "To", "singal", "that", "the", "sandox", "you", "have", "Posted", "is", "now", "uploaded", "." ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/sandbox.go#L59-L70
10,699
go-chef/chef
cookbook.go
String
func (c CookbookListResult) String() (out string) { for k, v := range c { out += fmt.Sprintf("%s => %s\n", k, v.Url) for _, i := range v.Versions { out += fmt.Sprintf(" * %s\n", i.Version) } } return out }
go
func (c CookbookListResult) String() (out string) { for k, v := range c { out += fmt.Sprintf("%s => %s\n", k, v.Url) for _, i := range v.Versions { out += fmt.Sprintf(" * %s\n", i.Version) } } return out }
[ "func", "(", "c", "CookbookListResult", ")", "String", "(", ")", "(", "out", "string", ")", "{", "for", "k", ",", "v", ":=", "range", "c", "{", "out", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "k", ",", "v", ".", "Url", ")", "\n", "for", "_", ",", "i", ":=", "range", "v", ".", "Versions", "{", "out", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "i", ".", "Version", ")", "\n", "}", "\n", "}", "\n", "return", "out", "\n", "}" ]
// String makes CookbookListResult implement the string result
[ "String", "makes", "CookbookListResult", "implement", "the", "string", "result" ]
cfd55cf96411cfa6ea658a3904fbcb8e40843e68
https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/cookbook.go#L81-L89