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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
142,500
trivago/gollum
main.go
startHealthCheckService
func startHealthCheckService() func() { if *flagHealthCheck == "" { return nil } address, err := parseAddress(*flagHealthCheck) if err != nil { logrus.WithError(err).Error("Failed to start health check service") return nil } thealthcheck.Configure(address) logrus.WithField("address", address).Info("Starting health check service") go thealthcheck.Start() // Add a static "ping" endpoint thealthcheck.AddEndpoint("/_PING_", func() (code int, body string) { return thealthcheck.StatusOK, "PONG" }) return thealthcheck.Stop }
go
func startHealthCheckService() func() { if *flagHealthCheck == "" { return nil } address, err := parseAddress(*flagHealthCheck) if err != nil { logrus.WithError(err).Error("Failed to start health check service") return nil } thealthcheck.Configure(address) logrus.WithField("address", address).Info("Starting health check service") go thealthcheck.Start() // Add a static "ping" endpoint thealthcheck.AddEndpoint("/_PING_", func() (code int, body string) { return thealthcheck.StatusOK, "PONG" }) return thealthcheck.Stop }
[ "func", "startHealthCheckService", "(", ")", "func", "(", ")", "{", "if", "*", "flagHealthCheck", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "address", ",", "err", ":=", "parseAddress", "(", "*", "flagHealthCheck", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "thealthcheck", ".", "Configure", "(", "address", ")", "\n\n", "logrus", ".", "WithField", "(", "\"", "\"", ",", "address", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "go", "thealthcheck", ".", "Start", "(", ")", "\n\n", "// Add a static \"ping\" endpoint", "thealthcheck", ".", "AddEndpoint", "(", "\"", "\"", ",", "func", "(", ")", "(", "code", "int", ",", "body", "string", ")", "{", "return", "thealthcheck", ".", "StatusOK", ",", "\"", "\"", "\n", "}", ")", "\n", "return", "thealthcheck", ".", "Stop", "\n", "}" ]
// startHealthCheckService creates a health check endpoint if requested. // The returned function should be deferred if not nil.
[ "startHealthCheckService", "creates", "a", "health", "check", "endpoint", "if", "requested", ".", "The", "returned", "function", "should", "be", "deferred", "if", "not", "nil", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/main.go#L261-L280
142,501
trivago/gollum
main.go
startMemoryProfiler
func startMemoryProfiler() func() { if *flagMemProfile == "" { return nil } return func() { file, err := os.Create(*flagMemProfile) if err != nil { logrus.WithError(err).Error("Failed to create memory profile results file") return } defer file.Close() logrus.WithField("file", *flagMemProfile).Info("Dumping memory profile") if err := pprof.WriteHeapProfile(file); err != nil { logrus.WithError(err).Error("Failed to write heap profile") } } }
go
func startMemoryProfiler() func() { if *flagMemProfile == "" { return nil } return func() { file, err := os.Create(*flagMemProfile) if err != nil { logrus.WithError(err).Error("Failed to create memory profile results file") return } defer file.Close() logrus.WithField("file", *flagMemProfile).Info("Dumping memory profile") if err := pprof.WriteHeapProfile(file); err != nil { logrus.WithError(err).Error("Failed to write heap profile") } } }
[ "func", "startMemoryProfiler", "(", ")", "func", "(", ")", "{", "if", "*", "flagMemProfile", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "return", "func", "(", ")", "{", "file", ",", "err", ":=", "os", ".", "Create", "(", "*", "flagMemProfile", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n\n", "logrus", ".", "WithField", "(", "\"", "\"", ",", "*", "flagMemProfile", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "pprof", ".", "WriteHeapProfile", "(", "file", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// startMemoryProfile enables the golang heap profiling process. // The returned function should be deferred if not nil.
[ "startMemoryProfile", "enables", "the", "golang", "heap", "profiling", "process", ".", "The", "returned", "function", "should", "be", "deferred", "if", "not", "nil", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/main.go#L312-L330
142,502
trivago/gollum
contrib/native/kafka/librdkafka/topicconfig.go
Set
func (c *TopicConfig) Set(key, value string) { nativeErr := new(ErrorHandle) if C.rd_kafka_topic_conf_set(c.handle, C.CString(key), C.CString(value), nativeErr.buffer(), nativeErr.len()) != 0 { Log.Print(nativeErr) } }
go
func (c *TopicConfig) Set(key, value string) { nativeErr := new(ErrorHandle) if C.rd_kafka_topic_conf_set(c.handle, C.CString(key), C.CString(value), nativeErr.buffer(), nativeErr.len()) != 0 { Log.Print(nativeErr) } }
[ "func", "(", "c", "*", "TopicConfig", ")", "Set", "(", "key", ",", "value", "string", ")", "{", "nativeErr", ":=", "new", "(", "ErrorHandle", ")", "\n", "if", "C", ".", "rd_kafka_topic_conf_set", "(", "c", ".", "handle", ",", "C", ".", "CString", "(", "key", ")", ",", "C", ".", "CString", "(", "value", ")", ",", "nativeErr", ".", "buffer", "(", ")", ",", "nativeErr", ".", "len", "(", ")", ")", "!=", "0", "{", "Log", ".", "Print", "(", "nativeErr", ")", "\n", "}", "\n", "}" ]
// Set sets a string value in this config
[ "Set", "sets", "a", "string", "value", "in", "this", "config" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/librdkafka/topicconfig.go#L57-L62
142,503
trivago/gollum
contrib/native/kafka/librdkafka/topicconfig.go
SetI
func (c *TopicConfig) SetI(key string, value int) { nativeErr := new(ErrorHandle) strValue := strconv.Itoa(value) if C.rd_kafka_topic_conf_set(c.handle, C.CString(key), C.CString(strValue), nativeErr.buffer(), nativeErr.len()) != 0 { Log.Print(nativeErr) } }
go
func (c *TopicConfig) SetI(key string, value int) { nativeErr := new(ErrorHandle) strValue := strconv.Itoa(value) if C.rd_kafka_topic_conf_set(c.handle, C.CString(key), C.CString(strValue), nativeErr.buffer(), nativeErr.len()) != 0 { Log.Print(nativeErr) } }
[ "func", "(", "c", "*", "TopicConfig", ")", "SetI", "(", "key", "string", ",", "value", "int", ")", "{", "nativeErr", ":=", "new", "(", "ErrorHandle", ")", "\n", "strValue", ":=", "strconv", ".", "Itoa", "(", "value", ")", "\n", "if", "C", ".", "rd_kafka_topic_conf_set", "(", "c", ".", "handle", ",", "C", ".", "CString", "(", "key", ")", ",", "C", ".", "CString", "(", "strValue", ")", ",", "nativeErr", ".", "buffer", "(", ")", ",", "nativeErr", ".", "len", "(", ")", ")", "!=", "0", "{", "Log", ".", "Print", "(", "nativeErr", ")", "\n", "}", "\n", "}" ]
// SetI sets an integer value in this config
[ "SetI", "sets", "an", "integer", "value", "in", "this", "config" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/librdkafka/topicconfig.go#L65-L71
142,504
trivago/gollum
core/simpleformatter.go
CanBeApplied
func (format *SimpleFormatter) CanBeApplied(msg *Message) bool { if format.SkipIfEmpty { return len(format.GetAppliedContent(msg)) > 0 } return true }
go
func (format *SimpleFormatter) CanBeApplied(msg *Message) bool { if format.SkipIfEmpty { return len(format.GetAppliedContent(msg)) > 0 } return true }
[ "func", "(", "format", "*", "SimpleFormatter", ")", "CanBeApplied", "(", "msg", "*", "Message", ")", "bool", "{", "if", "format", ".", "SkipIfEmpty", "{", "return", "len", "(", "format", ".", "GetAppliedContent", "(", "msg", ")", ")", ">", "0", "\n", "}", "\n", "return", "true", "\n", "}" ]
// CanBeApplied returns true if the formatter can be applied to this message
[ "CanBeApplied", "returns", "true", "if", "the", "formatter", "can", "be", "applied", "to", "this", "message" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleformatter.go#L53-L58
142,505
trivago/gollum
core/pluginconfigreader.go
NewPluginConfigReader
func NewPluginConfigReader(config *PluginConfig) PluginConfigReader { errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) return PluginConfigReader{ WithError: NewPluginConfigReaderWithError(config), Errors: &errors, } }
go
func NewPluginConfigReader(config *PluginConfig) PluginConfigReader { errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) return PluginConfigReader{ WithError: NewPluginConfigReaderWithError(config), Errors: &errors, } }
[ "func", "NewPluginConfigReader", "(", "config", "*", "PluginConfig", ")", "PluginConfigReader", "{", "errors", ":=", "tgo", ".", "NewErrorStack", "(", ")", "\n", "errors", ".", "SetFormat", "(", "tgo", ".", "ErrorStackFormatCSV", ")", "\n", "return", "PluginConfigReader", "{", "WithError", ":", "NewPluginConfigReaderWithError", "(", "config", ")", ",", "Errors", ":", "&", "errors", ",", "}", "\n", "}" ]
// NewPluginConfigReader creates a new reader on top of a given config.
[ "NewPluginConfigReader", "creates", "a", "new", "reader", "on", "top", "of", "a", "given", "config", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreader.go#L51-L58
142,506
trivago/gollum
core/pluginconfigreader.go
NewPluginConfigReaderFromReader
func NewPluginConfigReaderFromReader(reader PluginConfigReaderWithError) PluginConfigReader { errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) return PluginConfigReader{ WithError: reader, Errors: &errors, } }
go
func NewPluginConfigReaderFromReader(reader PluginConfigReaderWithError) PluginConfigReader { errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) return PluginConfigReader{ WithError: reader, Errors: &errors, } }
[ "func", "NewPluginConfigReaderFromReader", "(", "reader", "PluginConfigReaderWithError", ")", "PluginConfigReader", "{", "errors", ":=", "tgo", ".", "NewErrorStack", "(", ")", "\n", "errors", ".", "SetFormat", "(", "tgo", ".", "ErrorStackFormatCSV", ")", "\n", "return", "PluginConfigReader", "{", "WithError", ":", "reader", ",", "Errors", ":", "&", "errors", ",", "}", "\n", "}" ]
// NewPluginConfigReaderFromReader encapsulates a WithError reader that // is already attached to a config to read from.
[ "NewPluginConfigReaderFromReader", "encapsulates", "a", "WithError", "reader", "that", "is", "already", "attached", "to", "a", "config", "to", "read", "from", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreader.go#L62-L69
142,507
trivago/gollum
core/pluginconfigreader.go
GetModulatorArray
func (reader *PluginConfigReader) GetModulatorArray(key string, logger logrus.FieldLogger, defaultValue ModulatorArray) ModulatorArray { modulators, err := reader.WithError.GetModulatorArray(key, logger, defaultValue) reader.Errors.Push(err) return modulators }
go
func (reader *PluginConfigReader) GetModulatorArray(key string, logger logrus.FieldLogger, defaultValue ModulatorArray) ModulatorArray { modulators, err := reader.WithError.GetModulatorArray(key, logger, defaultValue) reader.Errors.Push(err) return modulators }
[ "func", "(", "reader", "*", "PluginConfigReader", ")", "GetModulatorArray", "(", "key", "string", ",", "logger", "logrus", ".", "FieldLogger", ",", "defaultValue", "ModulatorArray", ")", "ModulatorArray", "{", "modulators", ",", "err", ":=", "reader", ".", "WithError", ".", "GetModulatorArray", "(", "key", ",", "logger", ",", "defaultValue", ")", "\n", "reader", ".", "Errors", ".", "Push", "(", "err", ")", "\n", "return", "modulators", "\n", "}" ]
// GetModulatorArray reads an array of modulator plugins
[ "GetModulatorArray", "reads", "an", "array", "of", "modulator", "plugins" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreader.go#L189-L193
142,508
trivago/gollum
core/pluginconfigreader.go
Configure
func (reader *PluginConfigReader) Configure(item interface{}) error { itemValue := reflect.ValueOf(item) if itemValue.Kind() != reflect.Ptr { panic("Configure requires reference") } var logger logrus.FieldLogger if loggable, isScoped := item.(ScopedLogger); isScoped { logger = loggable.GetLogger() } reader.configureStruct(itemValue, logger) if confItem, isConfigurable := item.(Configurable); isConfigurable { confItem.Configure(*reader) } return reader.Errors.OrNil() }
go
func (reader *PluginConfigReader) Configure(item interface{}) error { itemValue := reflect.ValueOf(item) if itemValue.Kind() != reflect.Ptr { panic("Configure requires reference") } var logger logrus.FieldLogger if loggable, isScoped := item.(ScopedLogger); isScoped { logger = loggable.GetLogger() } reader.configureStruct(itemValue, logger) if confItem, isConfigurable := item.(Configurable); isConfigurable { confItem.Configure(*reader) } return reader.Errors.OrNil() }
[ "func", "(", "reader", "*", "PluginConfigReader", ")", "Configure", "(", "item", "interface", "{", "}", ")", "error", "{", "itemValue", ":=", "reflect", ".", "ValueOf", "(", "item", ")", "\n", "if", "itemValue", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "logger", "logrus", ".", "FieldLogger", "\n", "if", "loggable", ",", "isScoped", ":=", "item", ".", "(", "ScopedLogger", ")", ";", "isScoped", "{", "logger", "=", "loggable", ".", "GetLogger", "(", ")", "\n", "}", "\n\n", "reader", ".", "configureStruct", "(", "itemValue", ",", "logger", ")", "\n", "if", "confItem", ",", "isConfigurable", ":=", "item", ".", "(", "Configurable", ")", ";", "isConfigurable", "{", "confItem", ".", "Configure", "(", "*", "reader", ")", "\n", "}", "\n\n", "return", "reader", ".", "Errors", ".", "OrNil", "(", ")", "\n", "}" ]
// Configure will configure a given item by scanning for plugin struct tags and // calling the Configure method. Nested types will be traversed automatically.
[ "Configure", "will", "configure", "a", "given", "item", "by", "scanning", "for", "plugin", "struct", "tags", "and", "calling", "the", "Configure", "method", ".", "Nested", "types", "will", "be", "traversed", "automatically", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreader.go#L253-L270
142,509
trivago/gollum
core/formattermodulator.go
Modulate
func (formatterModulator *FormatterModulator) Modulate(msg *Message) ModulateResult { err := formatterModulator.ApplyFormatter(msg) if err != nil { logrus.Warning("FormatterModulator with error:", err) return ModulateResultDiscard } return ModulateResultContinue }
go
func (formatterModulator *FormatterModulator) Modulate(msg *Message) ModulateResult { err := formatterModulator.ApplyFormatter(msg) if err != nil { logrus.Warning("FormatterModulator with error:", err) return ModulateResultDiscard } return ModulateResultContinue }
[ "func", "(", "formatterModulator", "*", "FormatterModulator", ")", "Modulate", "(", "msg", "*", "Message", ")", "ModulateResult", "{", "err", ":=", "formatterModulator", ".", "ApplyFormatter", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warning", "(", "\"", "\"", ",", "err", ")", "\n", "return", "ModulateResultDiscard", "\n", "}", "\n\n", "return", "ModulateResultContinue", "\n", "}" ]
// Modulate implementation for Formatter
[ "Modulate", "implementation", "for", "Formatter" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/formattermodulator.go#L34-L42
142,510
trivago/gollum
core/formattermodulator.go
CanBeApplied
func (formatterModulator *FormatterModulator) CanBeApplied(msg *Message) bool { return formatterModulator.Formatter.CanBeApplied(msg) }
go
func (formatterModulator *FormatterModulator) CanBeApplied(msg *Message) bool { return formatterModulator.Formatter.CanBeApplied(msg) }
[ "func", "(", "formatterModulator", "*", "FormatterModulator", ")", "CanBeApplied", "(", "msg", "*", "Message", ")", "bool", "{", "return", "formatterModulator", ".", "Formatter", ".", "CanBeApplied", "(", "msg", ")", "\n", "}" ]
// CanBeApplied returns true if the array is not empty
[ "CanBeApplied", "returns", "true", "if", "the", "array", "is", "not", "empty" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/formattermodulator.go#L45-L47
142,511
trivago/gollum
core/formattermodulator.go
ApplyFormatter
func (formatterModulator *FormatterModulator) ApplyFormatter(msg *Message) error { if formatterModulator.CanBeApplied(msg) { return formatterModulator.Formatter.ApplyFormatter(msg) } return nil }
go
func (formatterModulator *FormatterModulator) ApplyFormatter(msg *Message) error { if formatterModulator.CanBeApplied(msg) { return formatterModulator.Formatter.ApplyFormatter(msg) } return nil }
[ "func", "(", "formatterModulator", "*", "FormatterModulator", ")", "ApplyFormatter", "(", "msg", "*", "Message", ")", "error", "{", "if", "formatterModulator", ".", "CanBeApplied", "(", "msg", ")", "{", "return", "formatterModulator", ".", "Formatter", ".", "ApplyFormatter", "(", "msg", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ApplyFormatter calls the Formatter.ApplyFormatter method
[ "ApplyFormatter", "calls", "the", "Formatter", ".", "ApplyFormatter", "method" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/formattermodulator.go#L50-L55
142,512
trivago/gollum
core/plugin.go
NewPluginRunState
func NewPluginRunState() *PluginRunState { stateToMetric[PluginStateInitializing].Inc(1) return &PluginRunState{ workers: nil, state: int32(PluginStateInitializing), } }
go
func NewPluginRunState() *PluginRunState { stateToMetric[PluginStateInitializing].Inc(1) return &PluginRunState{ workers: nil, state: int32(PluginStateInitializing), } }
[ "func", "NewPluginRunState", "(", ")", "*", "PluginRunState", "{", "stateToMetric", "[", "PluginStateInitializing", "]", ".", "Inc", "(", "1", ")", "\n", "return", "&", "PluginRunState", "{", "workers", ":", "nil", ",", "state", ":", "int32", "(", "PluginStateInitializing", ")", ",", "}", "\n", "}" ]
// NewPluginRunState creates a new plugin state helper
[ "NewPluginRunState", "creates", "a", "new", "plugin", "state", "helper" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/plugin.go#L111-L117
142,513
trivago/gollum
core/plugin.go
SetState
func (state *PluginRunState) SetState(nextState PluginState) { prevState := PluginState(atomic.SwapInt32(&state.state, int32(nextState))) if nextState != prevState { stateToMetric[prevState].Dec(1) stateToMetric[nextState].Inc(1) } }
go
func (state *PluginRunState) SetState(nextState PluginState) { prevState := PluginState(atomic.SwapInt32(&state.state, int32(nextState))) if nextState != prevState { stateToMetric[prevState].Dec(1) stateToMetric[nextState].Inc(1) } }
[ "func", "(", "state", "*", "PluginRunState", ")", "SetState", "(", "nextState", "PluginState", ")", "{", "prevState", ":=", "PluginState", "(", "atomic", ".", "SwapInt32", "(", "&", "state", ".", "state", ",", "int32", "(", "nextState", ")", ")", ")", "\n\n", "if", "nextState", "!=", "prevState", "{", "stateToMetric", "[", "prevState", "]", ".", "Dec", "(", "1", ")", "\n", "stateToMetric", "[", "nextState", "]", ".", "Inc", "(", "1", ")", "\n", "}", "\n", "}" ]
// SetState sets a new plugin state casted to the correct type
[ "SetState", "sets", "a", "new", "plugin", "state", "casted", "to", "the", "correct", "type" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/plugin.go#L130-L137
142,514
trivago/gollum
core/plugin.go
NewPluginWithConfig
func NewPluginWithConfig(config PluginConfig) (Plugin, error) { if len(config.Typename) == 0 { return nil, fmt.Errorf("plugin '%s' has no type set", config.ID) } obj, err := TypeRegistry.New(config.Typename) if err != nil { return nil, err } plugin, isPlugin := obj.(Plugin) if !isPlugin { return nil, fmt.Errorf("'%s' is not a plugin type", config.Typename) } reader := NewPluginConfigReader(&config) if err := reader.Configure(plugin); err != nil { return nil, err } // Note: The current YAML format does actually prevent this, but fallback // streams are being created during runtime. Those should be unique // but we might still run into bugs here. if len(config.ID) > 0 && !PluginRegistry.RegisterUnique(plugin, config.ID) { return nil, fmt.Errorf("plugin id '%s' must be unique", config.ID) } if err := config.Validate(); err != nil { return nil, err } return plugin, nil }
go
func NewPluginWithConfig(config PluginConfig) (Plugin, error) { if len(config.Typename) == 0 { return nil, fmt.Errorf("plugin '%s' has no type set", config.ID) } obj, err := TypeRegistry.New(config.Typename) if err != nil { return nil, err } plugin, isPlugin := obj.(Plugin) if !isPlugin { return nil, fmt.Errorf("'%s' is not a plugin type", config.Typename) } reader := NewPluginConfigReader(&config) if err := reader.Configure(plugin); err != nil { return nil, err } // Note: The current YAML format does actually prevent this, but fallback // streams are being created during runtime. Those should be unique // but we might still run into bugs here. if len(config.ID) > 0 && !PluginRegistry.RegisterUnique(plugin, config.ID) { return nil, fmt.Errorf("plugin id '%s' must be unique", config.ID) } if err := config.Validate(); err != nil { return nil, err } return plugin, nil }
[ "func", "NewPluginWithConfig", "(", "config", "PluginConfig", ")", "(", "Plugin", ",", "error", ")", "{", "if", "len", "(", "config", ".", "Typename", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "ID", ")", "\n", "}", "\n\n", "obj", ",", "err", ":=", "TypeRegistry", ".", "New", "(", "config", ".", "Typename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "plugin", ",", "isPlugin", ":=", "obj", ".", "(", "Plugin", ")", "\n", "if", "!", "isPlugin", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "Typename", ")", "\n", "}", "\n\n", "reader", ":=", "NewPluginConfigReader", "(", "&", "config", ")", "\n", "if", "err", ":=", "reader", ".", "Configure", "(", "plugin", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Note: The current YAML format does actually prevent this, but fallback", "// streams are being created during runtime. Those should be unique", "// but we might still run into bugs here.", "if", "len", "(", "config", ".", "ID", ")", ">", "0", "&&", "!", "PluginRegistry", ".", "RegisterUnique", "(", "plugin", ",", "config", ".", "ID", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "ID", ")", "\n", "}", "\n\n", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "plugin", ",", "nil", "\n", "}" ]
// NewPluginWithConfig creates a new plugin from the type information stored in its // config. This function internally calls NewPluginWithType.
[ "NewPluginWithConfig", "creates", "a", "new", "plugin", "from", "the", "type", "information", "stored", "in", "its", "config", ".", "This", "function", "internally", "calls", "NewPluginWithType", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/plugin.go#L159-L191
142,515
trivago/gollum
core/writerassembly.go
NewWriterAssembly
func NewWriterAssembly(writer io.Writer, flush func(*Message), modulator Modulator) WriterAssembly { return WriterAssembly{ writer: writer, modulator: modulator, flush: flush, writerGuard: new(sync.Mutex), } }
go
func NewWriterAssembly(writer io.Writer, flush func(*Message), modulator Modulator) WriterAssembly { return WriterAssembly{ writer: writer, modulator: modulator, flush: flush, writerGuard: new(sync.Mutex), } }
[ "func", "NewWriterAssembly", "(", "writer", "io", ".", "Writer", ",", "flush", "func", "(", "*", "Message", ")", ",", "modulator", "Modulator", ")", "WriterAssembly", "{", "return", "WriterAssembly", "{", "writer", ":", "writer", ",", "modulator", ":", "modulator", ",", "flush", ":", "flush", ",", "writerGuard", ":", "new", "(", "sync", ".", "Mutex", ")", ",", "}", "\n", "}" ]
// NewWriterAssembly creates a new adapter between io.Writer and the MessageBatch // AssemblyFunc function signature
[ "NewWriterAssembly", "creates", "a", "new", "adapter", "between", "io", ".", "Writer", "and", "the", "MessageBatch", "AssemblyFunc", "function", "signature" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/writerassembly.go#L37-L44
142,516
trivago/gollum
core/messagehelper.go
GetAppliedContentGetFunction
func GetAppliedContentGetFunction(applyTo string) GetAppliedContent { if applyTo != "" { return func(msg *Message) []byte { metadata := msg.TryGetMetadata() if metadata == nil { return []byte{} } return metadata.GetValue(applyTo) } } return func(msg *Message) []byte { return msg.GetPayload() } }
go
func GetAppliedContentGetFunction(applyTo string) GetAppliedContent { if applyTo != "" { return func(msg *Message) []byte { metadata := msg.TryGetMetadata() if metadata == nil { return []byte{} } return metadata.GetValue(applyTo) } } return func(msg *Message) []byte { return msg.GetPayload() } }
[ "func", "GetAppliedContentGetFunction", "(", "applyTo", "string", ")", "GetAppliedContent", "{", "if", "applyTo", "!=", "\"", "\"", "{", "return", "func", "(", "msg", "*", "Message", ")", "[", "]", "byte", "{", "metadata", ":=", "msg", ".", "TryGetMetadata", "(", ")", "\n", "if", "metadata", "==", "nil", "{", "return", "[", "]", "byte", "{", "}", "\n", "}", "\n", "return", "metadata", ".", "GetValue", "(", "applyTo", ")", "\n", "}", "\n", "}", "\n\n", "return", "func", "(", "msg", "*", "Message", ")", "[", "]", "byte", "{", "return", "msg", ".", "GetPayload", "(", ")", "\n", "}", "\n", "}" ]
// GetAppliedContentGetFunction returns a GetAppliedContent function
[ "GetAppliedContentGetFunction", "returns", "a", "GetAppliedContent", "function" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagehelper.go#L11-L25
142,517
trivago/gollum
core/messagehelper.go
GetAppliedContentSetFunction
func GetAppliedContentSetFunction(applyTo string) SetAppliedContent { if applyTo != "" { return func(msg *Message, content []byte) { if content == nil { msg.GetMetadata().Delete(applyTo) } else { msg.GetMetadata().SetValue(applyTo, content) } } } return func(msg *Message, content []byte) { if content == nil { msg.data.payload = msg.data.payload[:0] } else { msg.StorePayload(content) } } }
go
func GetAppliedContentSetFunction(applyTo string) SetAppliedContent { if applyTo != "" { return func(msg *Message, content []byte) { if content == nil { msg.GetMetadata().Delete(applyTo) } else { msg.GetMetadata().SetValue(applyTo, content) } } } return func(msg *Message, content []byte) { if content == nil { msg.data.payload = msg.data.payload[:0] } else { msg.StorePayload(content) } } }
[ "func", "GetAppliedContentSetFunction", "(", "applyTo", "string", ")", "SetAppliedContent", "{", "if", "applyTo", "!=", "\"", "\"", "{", "return", "func", "(", "msg", "*", "Message", ",", "content", "[", "]", "byte", ")", "{", "if", "content", "==", "nil", "{", "msg", ".", "GetMetadata", "(", ")", ".", "Delete", "(", "applyTo", ")", "\n", "}", "else", "{", "msg", ".", "GetMetadata", "(", ")", ".", "SetValue", "(", "applyTo", ",", "content", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "func", "(", "msg", "*", "Message", ",", "content", "[", "]", "byte", ")", "{", "if", "content", "==", "nil", "{", "msg", ".", "data", ".", "payload", "=", "msg", ".", "data", ".", "payload", "[", ":", "0", "]", "\n", "}", "else", "{", "msg", ".", "StorePayload", "(", "content", ")", "\n", "}", "\n", "}", "\n", "}" ]
// GetAppliedContentSetFunction returns SetAppliedContent function to store message content
[ "GetAppliedContentSetFunction", "returns", "SetAppliedContent", "function", "to", "store", "message", "content" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagehelper.go#L28-L46
142,518
trivago/gollum
core/components/rotateConfig.go
NewRotateConfig
func NewRotateConfig() RotateConfig { return RotateConfig{ Enabled: false, Timeout: 1440, SizeByte: 1024, Timestamp: "2006-01-02_15", ZeroPad: 0, Compress: false, AtHour: -1, AtMinute: -1, } }
go
func NewRotateConfig() RotateConfig { return RotateConfig{ Enabled: false, Timeout: 1440, SizeByte: 1024, Timestamp: "2006-01-02_15", ZeroPad: 0, Compress: false, AtHour: -1, AtMinute: -1, } }
[ "func", "NewRotateConfig", "(", ")", "RotateConfig", "{", "return", "RotateConfig", "{", "Enabled", ":", "false", ",", "Timeout", ":", "1440", ",", "SizeByte", ":", "1024", ",", "Timestamp", ":", "\"", "\"", ",", "ZeroPad", ":", "0", ",", "Compress", ":", "false", ",", "AtHour", ":", "-", "1", ",", "AtMinute", ":", "-", "1", ",", "}", "\n", "}" ]
// NewRotateConfig create and returns a RotateConfig with default settings
[ "NewRotateConfig", "create", "and", "returns", "a", "RotateConfig", "with", "default", "settings" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/rotateConfig.go#L67-L78
142,519
trivago/gollum
core/components/rotateConfig.go
Configure
func (rotate *RotateConfig) Configure(conf core.PluginConfigReader) { rotateAt := conf.GetString("Rotation/At", "") if rotateAt != "" { parts := strings.Split(rotateAt, ":") rotateAtHour, _ := strconv.ParseInt(parts[0], 10, 8) rotateAtMin, _ := strconv.ParseInt(parts[1], 10, 8) rotate.AtHour = int(rotateAtHour) rotate.AtMinute = int(rotateAtMin) } }
go
func (rotate *RotateConfig) Configure(conf core.PluginConfigReader) { rotateAt := conf.GetString("Rotation/At", "") if rotateAt != "" { parts := strings.Split(rotateAt, ":") rotateAtHour, _ := strconv.ParseInt(parts[0], 10, 8) rotateAtMin, _ := strconv.ParseInt(parts[1], 10, 8) rotate.AtHour = int(rotateAtHour) rotate.AtMinute = int(rotateAtMin) } }
[ "func", "(", "rotate", "*", "RotateConfig", ")", "Configure", "(", "conf", "core", ".", "PluginConfigReader", ")", "{", "rotateAt", ":=", "conf", ".", "GetString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "rotateAt", "!=", "\"", "\"", "{", "parts", ":=", "strings", ".", "Split", "(", "rotateAt", ",", "\"", "\"", ")", "\n", "rotateAtHour", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "parts", "[", "0", "]", ",", "10", ",", "8", ")", "\n", "rotateAtMin", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "parts", "[", "1", "]", ",", "10", ",", "8", ")", "\n\n", "rotate", ".", "AtHour", "=", "int", "(", "rotateAtHour", ")", "\n", "rotate", ".", "AtMinute", "=", "int", "(", "rotateAtMin", ")", "\n", "}", "\n", "}" ]
// Configure method for interface implementation
[ "Configure", "method", "for", "interface", "implementation" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/rotateConfig.go#L81-L91
142,520
trivago/gollum
core/messagequeue.go
Push
func (channel MessageQueue) Push(msg *Message, timeout time.Duration) (state MessageQueueResult) { defer func() { // Treat closed channels like timeouts if recover() != nil { state = MessageQueueTimeout } }() if timeout == 0 { channel <- msg return MessageQueueOk // ### return, done ### } start := time.Time{} spin := tsync.Spinner{} for { select { case channel <- msg: return MessageQueueOk // ### return, done ### default: switch { // Start timeout based retries case start.IsZero(): if timeout < 0 { return MessageQueueDiscard // ### return, discard and ignore ### } start = time.Now() spin = tsync.NewSpinner(tsync.SpinPriorityHigh) // Discard message after timeout case time.Since(start) > timeout: return MessageQueueTimeout // ### return, fallback ### // Yield and try again default: spin.Yield() } } } }
go
func (channel MessageQueue) Push(msg *Message, timeout time.Duration) (state MessageQueueResult) { defer func() { // Treat closed channels like timeouts if recover() != nil { state = MessageQueueTimeout } }() if timeout == 0 { channel <- msg return MessageQueueOk // ### return, done ### } start := time.Time{} spin := tsync.Spinner{} for { select { case channel <- msg: return MessageQueueOk // ### return, done ### default: switch { // Start timeout based retries case start.IsZero(): if timeout < 0 { return MessageQueueDiscard // ### return, discard and ignore ### } start = time.Now() spin = tsync.NewSpinner(tsync.SpinPriorityHigh) // Discard message after timeout case time.Since(start) > timeout: return MessageQueueTimeout // ### return, fallback ### // Yield and try again default: spin.Yield() } } } }
[ "func", "(", "channel", "MessageQueue", ")", "Push", "(", "msg", "*", "Message", ",", "timeout", "time", ".", "Duration", ")", "(", "state", "MessageQueueResult", ")", "{", "defer", "func", "(", ")", "{", "// Treat closed channels like timeouts", "if", "recover", "(", ")", "!=", "nil", "{", "state", "=", "MessageQueueTimeout", "\n", "}", "\n", "}", "(", ")", "\n\n", "if", "timeout", "==", "0", "{", "channel", "<-", "msg", "\n", "return", "MessageQueueOk", "// ### return, done ###", "\n", "}", "\n\n", "start", ":=", "time", ".", "Time", "{", "}", "\n", "spin", ":=", "tsync", ".", "Spinner", "{", "}", "\n", "for", "{", "select", "{", "case", "channel", "<-", "msg", ":", "return", "MessageQueueOk", "// ### return, done ###", "\n\n", "default", ":", "switch", "{", "// Start timeout based retries", "case", "start", ".", "IsZero", "(", ")", ":", "if", "timeout", "<", "0", "{", "return", "MessageQueueDiscard", "// ### return, discard and ignore ###", "\n", "}", "\n", "start", "=", "time", ".", "Now", "(", ")", "\n", "spin", "=", "tsync", ".", "NewSpinner", "(", "tsync", ".", "SpinPriorityHigh", ")", "\n\n", "// Discard message after timeout", "case", "time", ".", "Since", "(", "start", ")", ">", "timeout", ":", "return", "MessageQueueTimeout", "// ### return, fallback ###", "\n\n", "// Yield and try again", "default", ":", "spin", ".", "Yield", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Push adds a message to the MessageStream. // waiting for a timeout instead of just blocking. // Passing a timeout of -1 will discard the message. // Passing a timout of 0 will always block. // Messages that time out will be passed to the sent to the fallback queue if a Dropped // consumer exists. // The source parameter is used when a message is sent to the fallback, i.e. it is passed // to the Drop function.
[ "Push", "adds", "a", "message", "to", "the", "MessageStream", ".", "waiting", "for", "a", "timeout", "instead", "of", "just", "blocking", ".", "Passing", "a", "timeout", "of", "-", "1", "will", "discard", "the", "message", ".", "Passing", "a", "timout", "of", "0", "will", "always", "block", ".", "Messages", "that", "time", "out", "will", "be", "passed", "to", "the", "sent", "to", "the", "fallback", "queue", "if", "a", "Dropped", "consumer", "exists", ".", "The", "source", "parameter", "is", "used", "when", "a", "message", "is", "sent", "to", "the", "fallback", "i", ".", "e", ".", "it", "is", "passed", "to", "the", "Drop", "function", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagequeue.go#L50-L90
142,521
trivago/gollum
core/messagequeue.go
PopWithTimeout
func (channel MessageQueue) PopWithTimeout(maxDuration time.Duration) (*Message, bool) { timeout := time.NewTimer(maxDuration) select { case msg, more := <-channel: timeout.Stop() return msg, more case <-timeout.C: return nil, false } }
go
func (channel MessageQueue) PopWithTimeout(maxDuration time.Duration) (*Message, bool) { timeout := time.NewTimer(maxDuration) select { case msg, more := <-channel: timeout.Stop() return msg, more case <-timeout.C: return nil, false } }
[ "func", "(", "channel", "MessageQueue", ")", "PopWithTimeout", "(", "maxDuration", "time", ".", "Duration", ")", "(", "*", "Message", ",", "bool", ")", "{", "timeout", ":=", "time", ".", "NewTimer", "(", "maxDuration", ")", "\n", "select", "{", "case", "msg", ",", "more", ":=", "<-", "channel", ":", "timeout", ".", "Stop", "(", ")", "\n", "return", "msg", ",", "more", "\n", "case", "<-", "timeout", ".", "C", ":", "return", "nil", ",", "false", "\n", "}", "\n", "}" ]
// PopWithTimeout returns a message from the buffer with a runtime <= maxDuration. // If the channel is empty or the timout hit, the second return value is false.
[ "PopWithTimeout", "returns", "a", "message", "from", "the", "buffer", "with", "a", "runtime", "<", "=", "maxDuration", ".", "If", "the", "channel", "is", "empty", "or", "the", "timout", "hit", "the", "second", "return", "value", "is", "false", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagequeue.go#L108-L117
142,522
trivago/gollum
core/messagequeue.go
Pop
func (channel MessageQueue) Pop() (*Message, bool) { msg, more := <-channel return msg, more }
go
func (channel MessageQueue) Pop() (*Message, bool) { msg, more := <-channel return msg, more }
[ "func", "(", "channel", "MessageQueue", ")", "Pop", "(", ")", "(", "*", "Message", ",", "bool", ")", "{", "msg", ",", "more", ":=", "<-", "channel", "\n", "return", "msg", ",", "more", "\n", "}" ]
// Pop returns a message from the buffer
[ "Pop", "returns", "a", "message", "from", "the", "buffer" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagequeue.go#L120-L123
142,523
trivago/gollum
core/messagetracer.go
ActivateMessageTrace
func ActivateMessageTrace() { MessageTrace = func(msg *Message, pluginID string, comment string) { mt := messageTracer{ msg: msg, pluginID: pluginID, } mt.Dump(comment) } }
go
func ActivateMessageTrace() { MessageTrace = func(msg *Message, pluginID string, comment string) { mt := messageTracer{ msg: msg, pluginID: pluginID, } mt.Dump(comment) } }
[ "func", "ActivateMessageTrace", "(", ")", "{", "MessageTrace", "=", "func", "(", "msg", "*", "Message", ",", "pluginID", "string", ",", "comment", "string", ")", "{", "mt", ":=", "messageTracer", "{", "msg", ":", "msg", ",", "pluginID", ":", "pluginID", ",", "}", "\n\n", "mt", ".", "Dump", "(", "comment", ")", "\n", "}", "\n", "}" ]
// ActivateMessageTrace set a MessageTrace function to dump out the message trace
[ "ActivateMessageTrace", "set", "a", "MessageTrace", "function", "to", "dump", "out", "the", "message", "trace" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagetracer.go#L70-L79
142,524
trivago/gollum
core/messagetracer.go
Dump
func (mt *messageTracer) Dump(comment string) { if mt.msg.streamID == LogInternalStreamID || mt.msg.streamID == TraceInternalStreamID { return } var err error msgDump := mt.newMessageDump(mt.msg, comment) if StreamRegistry.IsStreamRegistered(TraceInternalStreamID) { err = mt.routeToTraceStream(msgDump) } else { err = mt.printMessageTrace(msgDump) } if err != nil { logrus.Error(err) } }
go
func (mt *messageTracer) Dump(comment string) { if mt.msg.streamID == LogInternalStreamID || mt.msg.streamID == TraceInternalStreamID { return } var err error msgDump := mt.newMessageDump(mt.msg, comment) if StreamRegistry.IsStreamRegistered(TraceInternalStreamID) { err = mt.routeToTraceStream(msgDump) } else { err = mt.printMessageTrace(msgDump) } if err != nil { logrus.Error(err) } }
[ "func", "(", "mt", "*", "messageTracer", ")", "Dump", "(", "comment", "string", ")", "{", "if", "mt", ".", "msg", ".", "streamID", "==", "LogInternalStreamID", "||", "mt", ".", "msg", ".", "streamID", "==", "TraceInternalStreamID", "{", "return", "\n", "}", "\n\n", "var", "err", "error", "\n", "msgDump", ":=", "mt", ".", "newMessageDump", "(", "mt", ".", "msg", ",", "comment", ")", "\n\n", "if", "StreamRegistry", ".", "IsStreamRegistered", "(", "TraceInternalStreamID", ")", "{", "err", "=", "mt", ".", "routeToTraceStream", "(", "msgDump", ")", "\n\n", "}", "else", "{", "err", "=", "mt", ".", "printMessageTrace", "(", "msgDump", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Error", "(", "err", ")", "\n", "}", "\n", "}" ]
// Dump creates a messageDump struct for the message trace
[ "Dump", "creates", "a", "messageDump", "struct", "for", "the", "message", "trace" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagetracer.go#L88-L106
142,525
trivago/gollum
producer/file/targetFile.go
NewTargetFile
func NewTargetFile(fileDir, fileName, fileExt string, permissions os.FileMode) TargetFile { return TargetFile{ fileDir, fileName, fileExt, fmt.Sprintf("%s/%s%s", fileDir, fileName, fileExt), permissions, } }
go
func NewTargetFile(fileDir, fileName, fileExt string, permissions os.FileMode) TargetFile { return TargetFile{ fileDir, fileName, fileExt, fmt.Sprintf("%s/%s%s", fileDir, fileName, fileExt), permissions, } }
[ "func", "NewTargetFile", "(", "fileDir", ",", "fileName", ",", "fileExt", "string", ",", "permissions", "os", ".", "FileMode", ")", "TargetFile", "{", "return", "TargetFile", "{", "fileDir", ",", "fileName", ",", "fileExt", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fileDir", ",", "fileName", ",", "fileExt", ")", ",", "permissions", ",", "}", "\n", "}" ]
// NewTargetFile returns a new TargetFile instance
[ "NewTargetFile", "returns", "a", "new", "TargetFile", "instance" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/targetFile.go#L38-L46
142,526
trivago/gollum
producer/file/targetFile.go
GetFinalPath
func (streamFile *TargetFile) GetFinalPath(rotate components.RotateConfig) string { return fmt.Sprintf("%s/%s", streamFile.dir, streamFile.GetFinalName(rotate)) }
go
func (streamFile *TargetFile) GetFinalPath(rotate components.RotateConfig) string { return fmt.Sprintf("%s/%s", streamFile.dir, streamFile.GetFinalName(rotate)) }
[ "func", "(", "streamFile", "*", "TargetFile", ")", "GetFinalPath", "(", "rotate", "components", ".", "RotateConfig", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "streamFile", ".", "dir", ",", "streamFile", ".", "GetFinalName", "(", "rotate", ")", ")", "\n", "}" ]
// GetFinalPath returns the final file path with possible rotations
[ "GetFinalPath", "returns", "the", "final", "file", "path", "with", "possible", "rotations" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/targetFile.go#L54-L56
142,527
trivago/gollum
producer/file/targetFile.go
GetFinalName
func (streamFile *TargetFile) GetFinalName(rotate components.RotateConfig) string { var logFileName string // Generate the log filename based on rotation, existing files, etc. if !rotate.Enabled { logFileName = fmt.Sprintf("%s%s", streamFile.name, streamFile.ext) } else { timestamp := time.Now().Format(rotate.Timestamp) signature := fmt.Sprintf("%s_%s", streamFile.name, timestamp) maxSuffix := uint64(0) files, _ := ioutil.ReadDir(streamFile.dir) for _, f := range files { if strings.HasPrefix(f.Name(), signature) { // Special case. // If there is no extension, counter stays at 0 // If there is an extension (and no count), parsing the "." will yield a counter of 0 // If there is a count, parsing it will work as intended counter := uint64(0) if len(f.Name()) > len(signature) { counter, _ = tstrings.Btoi([]byte(f.Name()[len(signature)+1:])) } if maxSuffix <= counter { maxSuffix = counter + 1 } } } if maxSuffix == 0 { logFileName = fmt.Sprintf("%s%s", signature, streamFile.ext) } else { formatString := "%s_%d%s" if rotate.ZeroPad > 0 { formatString = fmt.Sprintf("%%s_%%0%dd%%s", rotate.ZeroPad) } logFileName = fmt.Sprintf(formatString, signature, int(maxSuffix), streamFile.ext) } } return logFileName }
go
func (streamFile *TargetFile) GetFinalName(rotate components.RotateConfig) string { var logFileName string // Generate the log filename based on rotation, existing files, etc. if !rotate.Enabled { logFileName = fmt.Sprintf("%s%s", streamFile.name, streamFile.ext) } else { timestamp := time.Now().Format(rotate.Timestamp) signature := fmt.Sprintf("%s_%s", streamFile.name, timestamp) maxSuffix := uint64(0) files, _ := ioutil.ReadDir(streamFile.dir) for _, f := range files { if strings.HasPrefix(f.Name(), signature) { // Special case. // If there is no extension, counter stays at 0 // If there is an extension (and no count), parsing the "." will yield a counter of 0 // If there is a count, parsing it will work as intended counter := uint64(0) if len(f.Name()) > len(signature) { counter, _ = tstrings.Btoi([]byte(f.Name()[len(signature)+1:])) } if maxSuffix <= counter { maxSuffix = counter + 1 } } } if maxSuffix == 0 { logFileName = fmt.Sprintf("%s%s", signature, streamFile.ext) } else { formatString := "%s_%d%s" if rotate.ZeroPad > 0 { formatString = fmt.Sprintf("%%s_%%0%dd%%s", rotate.ZeroPad) } logFileName = fmt.Sprintf(formatString, signature, int(maxSuffix), streamFile.ext) } } return logFileName }
[ "func", "(", "streamFile", "*", "TargetFile", ")", "GetFinalName", "(", "rotate", "components", ".", "RotateConfig", ")", "string", "{", "var", "logFileName", "string", "\n\n", "// Generate the log filename based on rotation, existing files, etc.", "if", "!", "rotate", ".", "Enabled", "{", "logFileName", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "streamFile", ".", "name", ",", "streamFile", ".", "ext", ")", "\n", "}", "else", "{", "timestamp", ":=", "time", ".", "Now", "(", ")", ".", "Format", "(", "rotate", ".", "Timestamp", ")", "\n", "signature", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "streamFile", ".", "name", ",", "timestamp", ")", "\n", "maxSuffix", ":=", "uint64", "(", "0", ")", "\n\n", "files", ",", "_", ":=", "ioutil", ".", "ReadDir", "(", "streamFile", ".", "dir", ")", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "if", "strings", ".", "HasPrefix", "(", "f", ".", "Name", "(", ")", ",", "signature", ")", "{", "// Special case.", "// If there is no extension, counter stays at 0", "// If there is an extension (and no count), parsing the \".\" will yield a counter of 0", "// If there is a count, parsing it will work as intended", "counter", ":=", "uint64", "(", "0", ")", "\n", "if", "len", "(", "f", ".", "Name", "(", ")", ")", ">", "len", "(", "signature", ")", "{", "counter", ",", "_", "=", "tstrings", ".", "Btoi", "(", "[", "]", "byte", "(", "f", ".", "Name", "(", ")", "[", "len", "(", "signature", ")", "+", "1", ":", "]", ")", ")", "\n", "}", "\n\n", "if", "maxSuffix", "<=", "counter", "{", "maxSuffix", "=", "counter", "+", "1", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "maxSuffix", "==", "0", "{", "logFileName", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "signature", ",", "streamFile", ".", "ext", ")", "\n", "}", "else", "{", "formatString", ":=", "\"", "\"", "\n", "if", "rotate", ".", "ZeroPad", ">", "0", "{", "formatString", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rotate", ".", "ZeroPad", ")", "\n", "}", "\n", "logFileName", "=", "fmt", ".", "Sprintf", "(", "formatString", ",", "signature", ",", "int", "(", "maxSuffix", ")", ",", "streamFile", ".", "ext", ")", "\n", "}", "\n", "}", "\n\n", "return", "logFileName", "\n", "}" ]
// GetFinalName returns the final file name with possible rotations
[ "GetFinalName", "returns", "the", "final", "file", "name", "with", "possible", "rotations" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/targetFile.go#L59-L100
142,528
trivago/gollum
producer/file/targetFile.go
GetDir
func (streamFile *TargetFile) GetDir() (string, error) { // Assure path is existing if err := os.MkdirAll(streamFile.dir, streamFile.folderPermissions); err != nil { return "", fmt.Errorf("failed to create %s because of %s", streamFile.dir, err.Error()) } return streamFile.dir, nil }
go
func (streamFile *TargetFile) GetDir() (string, error) { // Assure path is existing if err := os.MkdirAll(streamFile.dir, streamFile.folderPermissions); err != nil { return "", fmt.Errorf("failed to create %s because of %s", streamFile.dir, err.Error()) } return streamFile.dir, nil }
[ "func", "(", "streamFile", "*", "TargetFile", ")", "GetDir", "(", ")", "(", "string", ",", "error", ")", "{", "// Assure path is existing", "if", "err", ":=", "os", ".", "MkdirAll", "(", "streamFile", ".", "dir", ",", "streamFile", ".", "folderPermissions", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "streamFile", ".", "dir", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "streamFile", ".", "dir", ",", "nil", "\n", "}" ]
// GetDir create file directory if it not exists and returns the dir name
[ "GetDir", "create", "file", "directory", "if", "it", "not", "exists", "and", "returns", "the", "dir", "name" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/targetFile.go#L103-L110
142,529
trivago/gollum
producer/file/targetFile.go
GetSymlinkPath
func (streamFile *TargetFile) GetSymlinkPath() string { return fmt.Sprintf("%s/%s_current%s", streamFile.dir, streamFile.name, streamFile.ext) }
go
func (streamFile *TargetFile) GetSymlinkPath() string { return fmt.Sprintf("%s/%s_current%s", streamFile.dir, streamFile.name, streamFile.ext) }
[ "func", "(", "streamFile", "*", "TargetFile", ")", "GetSymlinkPath", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "streamFile", ".", "dir", ",", "streamFile", ".", "name", ",", "streamFile", ".", "ext", ")", "\n", "}" ]
// GetSymlinkPath returns a symlink path for the current file
[ "GetSymlinkPath", "returns", "a", "symlink", "path", "for", "the", "current", "file" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/targetFile.go#L113-L115
142,530
trivago/gollum
consumer/syslogd.go
Consume
func (cons *Syslogd) Consume(workers *sync.WaitGroup) { server := syslog.NewServer() server.SetFormat(cons.format) server.SetHandler(cons) switch cons.protocol { case "unix": if err := server.ListenUnixgram(cons.address); err != nil { if errRemove := os.Remove(cons.address); errRemove != nil { cons.Logger.WithError(errRemove).Error("Failed to remove exisiting socket") } else { cons.Logger.Warning("Found existing socket ", cons.address, ". Removing.") err = server.ListenUnixgram(cons.address) } if err != nil { cons.Logger.WithError(err).Error("Failed to open unix://", cons.address) } } case "udp": if err := server.ListenUDP(cons.address); err != nil { cons.Logger.Error("Failed to open udp://", cons.address) } case "tcp": if err := server.ListenTCP(cons.address); err != nil { cons.Logger.Error("Failed to open tcp://", cons.address) } } server.Boot() defer server.Kill() cons.ControlLoop() server.Wait() }
go
func (cons *Syslogd) Consume(workers *sync.WaitGroup) { server := syslog.NewServer() server.SetFormat(cons.format) server.SetHandler(cons) switch cons.protocol { case "unix": if err := server.ListenUnixgram(cons.address); err != nil { if errRemove := os.Remove(cons.address); errRemove != nil { cons.Logger.WithError(errRemove).Error("Failed to remove exisiting socket") } else { cons.Logger.Warning("Found existing socket ", cons.address, ". Removing.") err = server.ListenUnixgram(cons.address) } if err != nil { cons.Logger.WithError(err).Error("Failed to open unix://", cons.address) } } case "udp": if err := server.ListenUDP(cons.address); err != nil { cons.Logger.Error("Failed to open udp://", cons.address) } case "tcp": if err := server.ListenTCP(cons.address); err != nil { cons.Logger.Error("Failed to open tcp://", cons.address) } } server.Boot() defer server.Kill() cons.ControlLoop() server.Wait() }
[ "func", "(", "cons", "*", "Syslogd", ")", "Consume", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "server", ":=", "syslog", ".", "NewServer", "(", ")", "\n", "server", ".", "SetFormat", "(", "cons", ".", "format", ")", "\n", "server", ".", "SetHandler", "(", "cons", ")", "\n\n", "switch", "cons", ".", "protocol", "{", "case", "\"", "\"", ":", "if", "err", ":=", "server", ".", "ListenUnixgram", "(", "cons", ".", "address", ")", ";", "err", "!=", "nil", "{", "if", "errRemove", ":=", "os", ".", "Remove", "(", "cons", ".", "address", ")", ";", "errRemove", "!=", "nil", "{", "cons", ".", "Logger", ".", "WithError", "(", "errRemove", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "else", "{", "cons", ".", "Logger", ".", "Warning", "(", "\"", "\"", ",", "cons", ".", "address", ",", "\"", "\"", ")", "\n", "err", "=", "server", ".", "ListenUnixgram", "(", "cons", ".", "address", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "cons", ".", "Logger", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ",", "cons", ".", "address", ")", "\n", "}", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "server", ".", "ListenUDP", "(", "cons", ".", "address", ")", ";", "err", "!=", "nil", "{", "cons", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "cons", ".", "address", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "server", ".", "ListenTCP", "(", "cons", ".", "address", ")", ";", "err", "!=", "nil", "{", "cons", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "cons", ".", "address", ")", "\n", "}", "\n", "}", "\n\n", "server", ".", "Boot", "(", ")", "\n", "defer", "server", ".", "Kill", "(", ")", "\n\n", "cons", ".", "ControlLoop", "(", ")", "\n", "server", ".", "Wait", "(", ")", "\n", "}" ]
// Consume opens a new syslog socket. // Messages are expected to be separated by \n.
[ "Consume", "opens", "a", "new", "syslog", "socket", ".", "Messages", "are", "expected", "to", "be", "separated", "by", "\\", "n", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/consumer/syslogd.go#L277-L311
142,531
trivago/gollum
core/pluginconfigreaderwitherror.go
GetLogger
func (reader PluginConfigReaderWithError) GetLogger() logrus.FieldLogger { return logrus.WithFields(logrus.Fields{ "PluginType": reader.config.Typename, "PluginID": reader.config.ID, }) }
go
func (reader PluginConfigReaderWithError) GetLogger() logrus.FieldLogger { return logrus.WithFields(logrus.Fields{ "PluginType": reader.config.Typename, "PluginID": reader.config.ID, }) }
[ "func", "(", "reader", "PluginConfigReaderWithError", ")", "GetLogger", "(", ")", "logrus", ".", "FieldLogger", "{", "return", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "reader", ".", "config", ".", "Typename", ",", "\"", "\"", ":", "reader", ".", "config", ".", "ID", ",", "}", ")", "\n", "}" ]
// GetLogger creates a logger scoped for the plugin contained in this config.
[ "GetLogger", "creates", "a", "logger", "scoped", "for", "the", "plugin", "contained", "in", "this", "config", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreaderwitherror.go#L43-L48
142,532
trivago/gollum
core/pluginconfigreaderwitherror.go
GetSubLogger
func (reader PluginConfigReaderWithError) GetSubLogger(subScope string) logrus.FieldLogger { return reader.GetLogger().WithField("Scope", subScope) }
go
func (reader PluginConfigReaderWithError) GetSubLogger(subScope string) logrus.FieldLogger { return reader.GetLogger().WithField("Scope", subScope) }
[ "func", "(", "reader", "PluginConfigReaderWithError", ")", "GetSubLogger", "(", "subScope", "string", ")", "logrus", ".", "FieldLogger", "{", "return", "reader", ".", "GetLogger", "(", ")", ".", "WithField", "(", "\"", "\"", ",", "subScope", ")", "\n", "}" ]
// GetSubLogger creates a logger scoped gor the plugin contained in this config, // with an additional subscope.
[ "GetSubLogger", "creates", "a", "logger", "scoped", "gor", "the", "plugin", "contained", "in", "this", "config", "with", "an", "additional", "subscope", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreaderwitherror.go#L52-L54
142,533
trivago/gollum
core/pluginconfigreaderwitherror.go
GetString
func (reader PluginConfigReaderWithError) GetString(key string, defaultValue string) (string, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { value, err := reader.config.Settings.String(key) return tstrings.Unescape(value), err } return defaultValue, nil }
go
func (reader PluginConfigReaderWithError) GetString(key string, defaultValue string) (string, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { value, err := reader.config.Settings.String(key) return tstrings.Unescape(value), err } return defaultValue, nil }
[ "func", "(", "reader", "PluginConfigReaderWithError", ")", "GetString", "(", "key", "string", ",", "defaultValue", "string", ")", "(", "string", ",", "error", ")", "{", "key", "=", "reader", ".", "config", ".", "registerKey", "(", "key", ")", "\n", "if", "reader", ".", "HasValue", "(", "key", ")", "{", "value", ",", "err", ":=", "reader", ".", "config", ".", "Settings", ".", "String", "(", "key", ")", "\n", "return", "tstrings", ".", "Unescape", "(", "value", ")", ",", "err", "\n", "}", "\n", "return", "defaultValue", ",", "nil", "\n", "}" ]
// GetString tries to read a string value from a PluginConfig. // If that value is not found defaultValue is returned.
[ "GetString", "tries", "to", "read", "a", "string", "value", "from", "a", "PluginConfig", ".", "If", "that", "value", "is", "not", "found", "defaultValue", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreaderwitherror.go#L76-L83
142,534
trivago/gollum
core/pluginconfigreaderwitherror.go
GetFloat
func (reader PluginConfigReaderWithError) GetFloat(key string, defaultValue float64) (float64, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { return reader.config.Settings.Float(key) } return defaultValue, nil }
go
func (reader PluginConfigReaderWithError) GetFloat(key string, defaultValue float64) (float64, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { return reader.config.Settings.Float(key) } return defaultValue, nil }
[ "func", "(", "reader", "PluginConfigReaderWithError", ")", "GetFloat", "(", "key", "string", ",", "defaultValue", "float64", ")", "(", "float64", ",", "error", ")", "{", "key", "=", "reader", ".", "config", ".", "registerKey", "(", "key", ")", "\n", "if", "reader", ".", "HasValue", "(", "key", ")", "{", "return", "reader", ".", "config", ".", "Settings", ".", "Float", "(", "key", ")", "\n", "}", "\n", "return", "defaultValue", ",", "nil", "\n", "}" ]
// GetFloat tries to read a float value from a PluginConfig. // If that value is not found defaultValue is returned.
[ "GetFloat", "tries", "to", "read", "a", "float", "value", "from", "a", "PluginConfig", ".", "If", "that", "value", "is", "not", "found", "defaultValue", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreaderwitherror.go#L130-L136
142,535
trivago/gollum
core/pluginconfigreaderwitherror.go
GetStreamID
func (reader PluginConfigReaderWithError) GetStreamID(key string, defaultValue MessageStreamID) (MessageStreamID, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { value, err := reader.config.Settings.String(key) if err != nil { return InvalidStreamID, err } return GetStreamID(value), nil } return defaultValue, nil }
go
func (reader PluginConfigReaderWithError) GetStreamID(key string, defaultValue MessageStreamID) (MessageStreamID, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { value, err := reader.config.Settings.String(key) if err != nil { return InvalidStreamID, err } return GetStreamID(value), nil } return defaultValue, nil }
[ "func", "(", "reader", "PluginConfigReaderWithError", ")", "GetStreamID", "(", "key", "string", ",", "defaultValue", "MessageStreamID", ")", "(", "MessageStreamID", ",", "error", ")", "{", "key", "=", "reader", ".", "config", ".", "registerKey", "(", "key", ")", "\n", "if", "reader", ".", "HasValue", "(", "key", ")", "{", "value", ",", "err", ":=", "reader", ".", "config", ".", "Settings", ".", "String", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "InvalidStreamID", ",", "err", "\n", "}", "\n", "return", "GetStreamID", "(", "value", ")", ",", "nil", "\n", "}", "\n", "return", "defaultValue", ",", "nil", "\n", "}" ]
// GetStreamID tries to read a StreamID value from a PluginConfig. // If that value is not found defaultValue is returned.
[ "GetStreamID", "tries", "to", "read", "a", "StreamID", "value", "from", "a", "PluginConfig", ".", "If", "that", "value", "is", "not", "found", "defaultValue", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreaderwitherror.go#L161-L171
142,536
trivago/gollum
core/pluginconfigreaderwitherror.go
GetModulatorArray
func (reader PluginConfigReaderWithError) GetModulatorArray(key string, logger logrus.FieldLogger, defaultValue ModulatorArray) (ModulatorArray, error) { modulators := []Modulator{} modPlugins, err := reader.GetPluginArray(key, []Plugin{}) if err != nil { return modulators, err } if len(modPlugins) == 0 { return modulators, nil } errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) for _, plugin := range modPlugins { if filter, isFilter := plugin.(Filter); isFilter { filterModulator := NewFilterModulator(filter) modulators = append(modulators, filterModulator) } else if formatter, isFormatter := plugin.(Formatter); isFormatter { formatterModulator := NewFormatterModulator(formatter) modulators = append(modulators, formatterModulator) } else if modulator, isModulator := plugin.(Modulator); isModulator { if modulator, isScopedModulator := plugin.(ScopedModulator); isScopedModulator { modulator.SetLogger(logger) } modulators = append(modulators, modulator) } else { errors.Pushf("Plugin '%T' is not a valid modulator", plugin) panic(errors.Top()) } } return modulators, errors.OrNil() }
go
func (reader PluginConfigReaderWithError) GetModulatorArray(key string, logger logrus.FieldLogger, defaultValue ModulatorArray) (ModulatorArray, error) { modulators := []Modulator{} modPlugins, err := reader.GetPluginArray(key, []Plugin{}) if err != nil { return modulators, err } if len(modPlugins) == 0 { return modulators, nil } errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) for _, plugin := range modPlugins { if filter, isFilter := plugin.(Filter); isFilter { filterModulator := NewFilterModulator(filter) modulators = append(modulators, filterModulator) } else if formatter, isFormatter := plugin.(Formatter); isFormatter { formatterModulator := NewFormatterModulator(formatter) modulators = append(modulators, formatterModulator) } else if modulator, isModulator := plugin.(Modulator); isModulator { if modulator, isScopedModulator := plugin.(ScopedModulator); isScopedModulator { modulator.SetLogger(logger) } modulators = append(modulators, modulator) } else { errors.Pushf("Plugin '%T' is not a valid modulator", plugin) panic(errors.Top()) } } return modulators, errors.OrNil() }
[ "func", "(", "reader", "PluginConfigReaderWithError", ")", "GetModulatorArray", "(", "key", "string", ",", "logger", "logrus", ".", "FieldLogger", ",", "defaultValue", "ModulatorArray", ")", "(", "ModulatorArray", ",", "error", ")", "{", "modulators", ":=", "[", "]", "Modulator", "{", "}", "\n\n", "modPlugins", ",", "err", ":=", "reader", ".", "GetPluginArray", "(", "key", ",", "[", "]", "Plugin", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "modulators", ",", "err", "\n", "}", "\n", "if", "len", "(", "modPlugins", ")", "==", "0", "{", "return", "modulators", ",", "nil", "\n", "}", "\n\n", "errors", ":=", "tgo", ".", "NewErrorStack", "(", ")", "\n", "errors", ".", "SetFormat", "(", "tgo", ".", "ErrorStackFormatCSV", ")", "\n\n", "for", "_", ",", "plugin", ":=", "range", "modPlugins", "{", "if", "filter", ",", "isFilter", ":=", "plugin", ".", "(", "Filter", ")", ";", "isFilter", "{", "filterModulator", ":=", "NewFilterModulator", "(", "filter", ")", "\n", "modulators", "=", "append", "(", "modulators", ",", "filterModulator", ")", "\n", "}", "else", "if", "formatter", ",", "isFormatter", ":=", "plugin", ".", "(", "Formatter", ")", ";", "isFormatter", "{", "formatterModulator", ":=", "NewFormatterModulator", "(", "formatter", ")", "\n", "modulators", "=", "append", "(", "modulators", ",", "formatterModulator", ")", "\n", "}", "else", "if", "modulator", ",", "isModulator", ":=", "plugin", ".", "(", "Modulator", ")", ";", "isModulator", "{", "if", "modulator", ",", "isScopedModulator", ":=", "plugin", ".", "(", "ScopedModulator", ")", ";", "isScopedModulator", "{", "modulator", ".", "SetLogger", "(", "logger", ")", "\n", "}", "\n", "modulators", "=", "append", "(", "modulators", ",", "modulator", ")", "\n", "}", "else", "{", "errors", ".", "Pushf", "(", "\"", "\"", ",", "plugin", ")", "\n", "panic", "(", "errors", ".", "Top", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "modulators", ",", "errors", ".", "OrNil", "(", ")", "\n", "}" ]
// GetModulatorArray returns an array of modulator plugins.
[ "GetModulatorArray", "returns", "an", "array", "of", "modulator", "plugins", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreaderwitherror.go#L277-L311
142,537
trivago/gollum
core/pluginconfigreaderwitherror.go
GetStringArray
func (reader PluginConfigReaderWithError) GetStringArray(key string, defaultValue []string) ([]string, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { return reader.config.Settings.StringArray(key) } return defaultValue, nil }
go
func (reader PluginConfigReaderWithError) GetStringArray(key string, defaultValue []string) ([]string, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { return reader.config.Settings.StringArray(key) } return defaultValue, nil }
[ "func", "(", "reader", "PluginConfigReaderWithError", ")", "GetStringArray", "(", "key", "string", ",", "defaultValue", "[", "]", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "key", "=", "reader", ".", "config", ".", "registerKey", "(", "key", ")", "\n", "if", "reader", ".", "HasValue", "(", "key", ")", "{", "return", "reader", ".", "config", ".", "Settings", ".", "StringArray", "(", "key", ")", "\n", "}", "\n", "return", "defaultValue", ",", "nil", "\n", "}" ]
// GetStringArray tries to read a string array from a // PluginConfig. If that value is not found defaultValue is returned.
[ "GetStringArray", "tries", "to", "read", "a", "string", "array", "from", "a", "PluginConfig", ".", "If", "that", "value", "is", "not", "found", "defaultValue", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreaderwitherror.go#L370-L376
142,538
trivago/gollum
core/pluginconfigreaderwitherror.go
GetStringMap
func (reader PluginConfigReaderWithError) GetStringMap(key string, defaultValue map[string]string) (map[string]string, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { return reader.config.Settings.StringMap(key) } return defaultValue, nil }
go
func (reader PluginConfigReaderWithError) GetStringMap(key string, defaultValue map[string]string) (map[string]string, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { return reader.config.Settings.StringMap(key) } return defaultValue, nil }
[ "func", "(", "reader", "PluginConfigReaderWithError", ")", "GetStringMap", "(", "key", "string", ",", "defaultValue", "map", "[", "string", "]", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "key", "=", "reader", ".", "config", ".", "registerKey", "(", "key", ")", "\n", "if", "reader", ".", "HasValue", "(", "key", ")", "{", "return", "reader", ".", "config", ".", "Settings", ".", "StringMap", "(", "key", ")", "\n", "}", "\n", "return", "defaultValue", ",", "nil", "\n", "}" ]
// GetStringMap tries to read a string to string map from a // PluginConfig. If the key is not found defaultValue is returned.
[ "GetStringMap", "tries", "to", "read", "a", "string", "to", "string", "map", "from", "a", "PluginConfig", ".", "If", "the", "key", "is", "not", "found", "defaultValue", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreaderwitherror.go#L380-L386
142,539
trivago/gollum
core/pluginconfigreaderwitherror.go
GetStreamArray
func (reader PluginConfigReaderWithError) GetStreamArray(key string, defaultValue []MessageStreamID) ([]MessageStreamID, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { values, err := reader.GetStringArray(key, []string{}) if err != nil { return nil, err } streamArray := []MessageStreamID{} for _, streamName := range values { streamArray = append(streamArray, GetStreamID(streamName)) } return streamArray, nil } return defaultValue, nil }
go
func (reader PluginConfigReaderWithError) GetStreamArray(key string, defaultValue []MessageStreamID) ([]MessageStreamID, error) { key = reader.config.registerKey(key) if reader.HasValue(key) { values, err := reader.GetStringArray(key, []string{}) if err != nil { return nil, err } streamArray := []MessageStreamID{} for _, streamName := range values { streamArray = append(streamArray, GetStreamID(streamName)) } return streamArray, nil } return defaultValue, nil }
[ "func", "(", "reader", "PluginConfigReaderWithError", ")", "GetStreamArray", "(", "key", "string", ",", "defaultValue", "[", "]", "MessageStreamID", ")", "(", "[", "]", "MessageStreamID", ",", "error", ")", "{", "key", "=", "reader", ".", "config", ".", "registerKey", "(", "key", ")", "\n", "if", "reader", ".", "HasValue", "(", "key", ")", "{", "values", ",", "err", ":=", "reader", ".", "GetStringArray", "(", "key", ",", "[", "]", "string", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "streamArray", ":=", "[", "]", "MessageStreamID", "{", "}", "\n", "for", "_", ",", "streamName", ":=", "range", "values", "{", "streamArray", "=", "append", "(", "streamArray", ",", "GetStreamID", "(", "streamName", ")", ")", "\n", "}", "\n", "return", "streamArray", ",", "nil", "\n", "}", "\n\n", "return", "defaultValue", ",", "nil", "\n", "}" ]
// GetStreamArray tries to read a string array from a pluginconfig // and translates all values to streamIds. If the key is not found defaultValue // is returned.
[ "GetStreamArray", "tries", "to", "read", "a", "string", "array", "from", "a", "pluginconfig", "and", "translates", "all", "values", "to", "streamIds", ".", "If", "the", "key", "is", "not", "found", "defaultValue", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreaderwitherror.go#L391-L406
142,540
trivago/gollum
core/pluginconfigreaderwitherror.go
GetStreamRoutes
func (reader PluginConfigReaderWithError) GetStreamRoutes(key string, defaultValue map[MessageStreamID][]MessageStreamID) (map[MessageStreamID][]MessageStreamID, error) { key = reader.config.registerKey(key) if !reader.HasValue(key) { return defaultValue, nil } streamRoute := make(map[MessageStreamID][]MessageStreamID) value, err := reader.config.Settings.StringArrayMap(key) if err != nil { return nil, err } for sourceName, targets := range value { sourceStream := GetStreamID(sourceName) targetIds := []MessageStreamID{} for _, targetName := range targets { targetIds = append(targetIds, GetStreamID(targetName)) } streamRoute[sourceStream] = targetIds } return streamRoute, nil }
go
func (reader PluginConfigReaderWithError) GetStreamRoutes(key string, defaultValue map[MessageStreamID][]MessageStreamID) (map[MessageStreamID][]MessageStreamID, error) { key = reader.config.registerKey(key) if !reader.HasValue(key) { return defaultValue, nil } streamRoute := make(map[MessageStreamID][]MessageStreamID) value, err := reader.config.Settings.StringArrayMap(key) if err != nil { return nil, err } for sourceName, targets := range value { sourceStream := GetStreamID(sourceName) targetIds := []MessageStreamID{} for _, targetName := range targets { targetIds = append(targetIds, GetStreamID(targetName)) } streamRoute[sourceStream] = targetIds } return streamRoute, nil }
[ "func", "(", "reader", "PluginConfigReaderWithError", ")", "GetStreamRoutes", "(", "key", "string", ",", "defaultValue", "map", "[", "MessageStreamID", "]", "[", "]", "MessageStreamID", ")", "(", "map", "[", "MessageStreamID", "]", "[", "]", "MessageStreamID", ",", "error", ")", "{", "key", "=", "reader", ".", "config", ".", "registerKey", "(", "key", ")", "\n", "if", "!", "reader", ".", "HasValue", "(", "key", ")", "{", "return", "defaultValue", ",", "nil", "\n", "}", "\n\n", "streamRoute", ":=", "make", "(", "map", "[", "MessageStreamID", "]", "[", "]", "MessageStreamID", ")", "\n", "value", ",", "err", ":=", "reader", ".", "config", ".", "Settings", ".", "StringArrayMap", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "sourceName", ",", "targets", ":=", "range", "value", "{", "sourceStream", ":=", "GetStreamID", "(", "sourceName", ")", "\n", "targetIds", ":=", "[", "]", "MessageStreamID", "{", "}", "\n", "for", "_", ",", "targetName", ":=", "range", "targets", "{", "targetIds", "=", "append", "(", "targetIds", ",", "GetStreamID", "(", "targetName", ")", ")", "\n", "}", "\n\n", "streamRoute", "[", "sourceStream", "]", "=", "targetIds", "\n", "}", "\n\n", "return", "streamRoute", ",", "nil", "\n", "}" ]
// GetStreamRoutes tries to read a stream to stream map from a // plugin config. If no routes are defined an empty map is returned
[ "GetStreamRoutes", "tries", "to", "read", "a", "stream", "to", "stream", "map", "from", "a", "plugin", "config", ".", "If", "no", "routes", "are", "defined", "an", "empty", "map", "is", "returned" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfigreaderwitherror.go#L434-L457
142,541
trivago/gollum
consumer/kafka.go
startAllConsumers
func (cons *Kafka) startAllConsumers() error { var err error if cons.group != "" { cons.groupClient, err = cluster.NewClient(cons.servers, cons.groupConfig) if err != nil { return err } go cons.readFromGroup() return nil // ### return, group processing ### } cons.client, err = kafka.NewClient(cons.servers, cons.config) if err != nil { return err } cons.consumer, err = kafka.NewConsumerFromClient(cons.client) if err != nil { return err } cons.startReadTopic(cons.topic) return nil }
go
func (cons *Kafka) startAllConsumers() error { var err error if cons.group != "" { cons.groupClient, err = cluster.NewClient(cons.servers, cons.groupConfig) if err != nil { return err } go cons.readFromGroup() return nil // ### return, group processing ### } cons.client, err = kafka.NewClient(cons.servers, cons.config) if err != nil { return err } cons.consumer, err = kafka.NewConsumerFromClient(cons.client) if err != nil { return err } cons.startReadTopic(cons.topic) return nil }
[ "func", "(", "cons", "*", "Kafka", ")", "startAllConsumers", "(", ")", "error", "{", "var", "err", "error", "\n\n", "if", "cons", ".", "group", "!=", "\"", "\"", "{", "cons", ".", "groupClient", ",", "err", "=", "cluster", ".", "NewClient", "(", "cons", ".", "servers", ",", "cons", ".", "groupConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "go", "cons", ".", "readFromGroup", "(", ")", "\n", "return", "nil", "// ### return, group processing ###", "\n", "}", "\n\n", "cons", ".", "client", ",", "err", "=", "kafka", ".", "NewClient", "(", "cons", ".", "servers", ",", "cons", ".", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cons", ".", "consumer", ",", "err", "=", "kafka", ".", "NewConsumerFromClient", "(", "cons", ".", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cons", ".", "startReadTopic", "(", "cons", ".", "topic", ")", "\n\n", "return", "nil", "\n", "}" ]
// Start one consumer per partition as a go routine
[ "Start", "one", "consumer", "per", "partition", "as", "a", "go", "routine" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/consumer/kafka.go#L564-L590
142,542
trivago/gollum
consumer/kafka.go
dumpIndex
func (cons *Kafka) dumpIndex() { if cons.offsetFile != "" { encodedOffsets := make(map[string]int64) for k := range cons.offsets { encodedOffsets[strconv.Itoa(int(k))] = atomic.LoadInt64(cons.offsets[k]) } data, err := json.Marshal(encodedOffsets) if err != nil { cons.Logger.WithError(err).Error("Kafka index file write error") return } fileDir := path.Dir(cons.offsetFile) if err := os.MkdirAll(fileDir, cons.folderPermissions); err != nil { cons.Logger.WithError(err).Errorf("Failed to create %s", fileDir) return } if err := ioutil.WriteFile(cons.offsetFile, data, 0644); err != nil { cons.Logger.WithError(err).Error("Failed to write offsets") } } }
go
func (cons *Kafka) dumpIndex() { if cons.offsetFile != "" { encodedOffsets := make(map[string]int64) for k := range cons.offsets { encodedOffsets[strconv.Itoa(int(k))] = atomic.LoadInt64(cons.offsets[k]) } data, err := json.Marshal(encodedOffsets) if err != nil { cons.Logger.WithError(err).Error("Kafka index file write error") return } fileDir := path.Dir(cons.offsetFile) if err := os.MkdirAll(fileDir, cons.folderPermissions); err != nil { cons.Logger.WithError(err).Errorf("Failed to create %s", fileDir) return } if err := ioutil.WriteFile(cons.offsetFile, data, 0644); err != nil { cons.Logger.WithError(err).Error("Failed to write offsets") } } }
[ "func", "(", "cons", "*", "Kafka", ")", "dumpIndex", "(", ")", "{", "if", "cons", ".", "offsetFile", "!=", "\"", "\"", "{", "encodedOffsets", ":=", "make", "(", "map", "[", "string", "]", "int64", ")", "\n", "for", "k", ":=", "range", "cons", ".", "offsets", "{", "encodedOffsets", "[", "strconv", ".", "Itoa", "(", "int", "(", "k", ")", ")", "]", "=", "atomic", ".", "LoadInt64", "(", "cons", ".", "offsets", "[", "k", "]", ")", "\n", "}", "\n\n", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "encodedOffsets", ")", "\n", "if", "err", "!=", "nil", "{", "cons", ".", "Logger", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "fileDir", ":=", "path", ".", "Dir", "(", "cons", ".", "offsetFile", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "fileDir", ",", "cons", ".", "folderPermissions", ")", ";", "err", "!=", "nil", "{", "cons", ".", "Logger", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "fileDir", ")", "\n", "return", "\n", "}", "\n\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "cons", ".", "offsetFile", ",", "data", ",", "0644", ")", ";", "err", "!=", "nil", "{", "cons", ".", "Logger", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Write index file to disc
[ "Write", "index", "file", "to", "disc" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/consumer/kafka.go#L593-L616
142,543
trivago/gollum
consumer/kafka.go
Consume
func (cons *Kafka) Consume(workers *sync.WaitGroup) { cons.SetWorkerWaitGroup(workers) if err := cons.startAllConsumers(); err != nil { cons.Logger.WithError(err).Error("Kafka client error") time.AfterFunc(cons.config.Net.DialTimeout, func() { cons.Consume(workers) }) return } defer func() { cons.client.Close() cons.dumpIndex() }() cons.TickerControlLoop(cons.persistTimeout, cons.dumpIndex) }
go
func (cons *Kafka) Consume(workers *sync.WaitGroup) { cons.SetWorkerWaitGroup(workers) if err := cons.startAllConsumers(); err != nil { cons.Logger.WithError(err).Error("Kafka client error") time.AfterFunc(cons.config.Net.DialTimeout, func() { cons.Consume(workers) }) return } defer func() { cons.client.Close() cons.dumpIndex() }() cons.TickerControlLoop(cons.persistTimeout, cons.dumpIndex) }
[ "func", "(", "cons", "*", "Kafka", ")", "Consume", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "cons", ".", "SetWorkerWaitGroup", "(", "workers", ")", "\n\n", "if", "err", ":=", "cons", ".", "startAllConsumers", "(", ")", ";", "err", "!=", "nil", "{", "cons", ".", "Logger", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "time", ".", "AfterFunc", "(", "cons", ".", "config", ".", "Net", ".", "DialTimeout", ",", "func", "(", ")", "{", "cons", ".", "Consume", "(", "workers", ")", "}", ")", "\n", "return", "\n", "}", "\n\n", "defer", "func", "(", ")", "{", "cons", ".", "client", ".", "Close", "(", ")", "\n", "cons", ".", "dumpIndex", "(", ")", "\n", "}", "(", ")", "\n\n", "cons", ".", "TickerControlLoop", "(", "cons", ".", "persistTimeout", ",", "cons", ".", "dumpIndex", ")", "\n", "}" ]
// Consume starts a kafka consumer per partition for this topic
[ "Consume", "starts", "a", "kafka", "consumer", "per", "partition", "for", "this", "topic" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/consumer/kafka.go#L619-L634
142,544
trivago/gollum
format/jsontoinflux10.go
toUnixTime
func (format *JSONToInflux10) toUnixTime(timeString string) (int64, error) { if format.timeFormat == "unix" { return strconv.ParseInt(timeString, 10, 64) } t, err := time.Parse(format.timeFormat, timeString) if err != nil { return 0, err } return t.Unix(), nil }
go
func (format *JSONToInflux10) toUnixTime(timeString string) (int64, error) { if format.timeFormat == "unix" { return strconv.ParseInt(timeString, 10, 64) } t, err := time.Parse(format.timeFormat, timeString) if err != nil { return 0, err } return t.Unix(), nil }
[ "func", "(", "format", "*", "JSONToInflux10", ")", "toUnixTime", "(", "timeString", "string", ")", "(", "int64", ",", "error", ")", "{", "if", "format", ".", "timeFormat", "==", "\"", "\"", "{", "return", "strconv", ".", "ParseInt", "(", "timeString", ",", "10", ",", "64", ")", "\n", "}", "\n", "t", ",", "err", ":=", "time", ".", "Parse", "(", "format", ".", "timeFormat", ",", "timeString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "t", ".", "Unix", "(", ")", ",", "nil", "\n", "}" ]
// Return the time field as a unix timestamp
[ "Return", "the", "time", "field", "as", "a", "unix", "timestamp" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/format/jsontoinflux10.go#L132-L141
142,545
trivago/gollum
format/jsontoinflux10.go
ApplyFormatter
func (format *JSONToInflux10) ApplyFormatter(msg *core.Message) error { content := format.GetAppliedContent(msg) values := make(tcontainer.MarshalMap) err := json.Unmarshal(content, &values) if err != nil { format.Logger.Warningf("JSON parser error: %s, Message: %s", err, content) return err } var timestamp int64 if val, ok := values[format.timeField]; ok { timestamp, err = format.toUnixTime(val.(string)) if err != nil { format.Logger.Error("Invalid time format in message:", err) } delete(values, format.timeField) } else { timestamp = time.Now().Unix() } measurement, measurementFound := values[format.measurement] if !measurementFound { return fmt.Errorf("required field for measurement (%s) not found in payload", format.measurement) } delete(values, format.measurement) fields := make(map[string]interface{}) tags := make(map[string]interface{}) for k, v := range values { if _, ignore := format.ignore[k]; ignore { continue } key := format.escapeMetadata(k) if _, isTag := format.tags[k]; isTag { tags[key] = format.escapeMetadata(v.(string)) } else { fields[key] = format.escapeFieldValue(v.(string)) } } measurementString := format.escapeMeasurement(measurement.(string)) tagsString := format.joinMap(tags) if len(tagsString) > 0 { // Only add comma between measurement and tags if tags are not empty. // See https://docs.influxdata.com/influxdb/v1.2/write_protocols/line_protocol_reference/ tagsString = "," + tagsString } fieldsString := format.joinMap(fields) line := fmt.Sprintf( `%s%s %s %d`, measurementString, tagsString, fieldsString, timestamp) format.SetAppliedContent(msg, []byte(line)) return nil }
go
func (format *JSONToInflux10) ApplyFormatter(msg *core.Message) error { content := format.GetAppliedContent(msg) values := make(tcontainer.MarshalMap) err := json.Unmarshal(content, &values) if err != nil { format.Logger.Warningf("JSON parser error: %s, Message: %s", err, content) return err } var timestamp int64 if val, ok := values[format.timeField]; ok { timestamp, err = format.toUnixTime(val.(string)) if err != nil { format.Logger.Error("Invalid time format in message:", err) } delete(values, format.timeField) } else { timestamp = time.Now().Unix() } measurement, measurementFound := values[format.measurement] if !measurementFound { return fmt.Errorf("required field for measurement (%s) not found in payload", format.measurement) } delete(values, format.measurement) fields := make(map[string]interface{}) tags := make(map[string]interface{}) for k, v := range values { if _, ignore := format.ignore[k]; ignore { continue } key := format.escapeMetadata(k) if _, isTag := format.tags[k]; isTag { tags[key] = format.escapeMetadata(v.(string)) } else { fields[key] = format.escapeFieldValue(v.(string)) } } measurementString := format.escapeMeasurement(measurement.(string)) tagsString := format.joinMap(tags) if len(tagsString) > 0 { // Only add comma between measurement and tags if tags are not empty. // See https://docs.influxdata.com/influxdb/v1.2/write_protocols/line_protocol_reference/ tagsString = "," + tagsString } fieldsString := format.joinMap(fields) line := fmt.Sprintf( `%s%s %s %d`, measurementString, tagsString, fieldsString, timestamp) format.SetAppliedContent(msg, []byte(line)) return nil }
[ "func", "(", "format", "*", "JSONToInflux10", ")", "ApplyFormatter", "(", "msg", "*", "core", ".", "Message", ")", "error", "{", "content", ":=", "format", ".", "GetAppliedContent", "(", "msg", ")", "\n\n", "values", ":=", "make", "(", "tcontainer", ".", "MarshalMap", ")", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "content", ",", "&", "values", ")", "\n\n", "if", "err", "!=", "nil", "{", "format", ".", "Logger", ".", "Warningf", "(", "\"", "\"", ",", "err", ",", "content", ")", "\n", "return", "err", "\n", "}", "\n\n", "var", "timestamp", "int64", "\n", "if", "val", ",", "ok", ":=", "values", "[", "format", ".", "timeField", "]", ";", "ok", "{", "timestamp", ",", "err", "=", "format", ".", "toUnixTime", "(", "val", ".", "(", "string", ")", ")", "\n", "if", "err", "!=", "nil", "{", "format", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "delete", "(", "values", ",", "format", ".", "timeField", ")", "\n", "}", "else", "{", "timestamp", "=", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "\n", "}", "\n\n", "measurement", ",", "measurementFound", ":=", "values", "[", "format", ".", "measurement", "]", "\n", "if", "!", "measurementFound", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "format", ".", "measurement", ")", "\n", "}", "\n\n", "delete", "(", "values", ",", "format", ".", "measurement", ")", "\n\n", "fields", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "tags", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "k", ",", "v", ":=", "range", "values", "{", "if", "_", ",", "ignore", ":=", "format", ".", "ignore", "[", "k", "]", ";", "ignore", "{", "continue", "\n", "}", "\n", "key", ":=", "format", ".", "escapeMetadata", "(", "k", ")", "\n", "if", "_", ",", "isTag", ":=", "format", ".", "tags", "[", "k", "]", ";", "isTag", "{", "tags", "[", "key", "]", "=", "format", ".", "escapeMetadata", "(", "v", ".", "(", "string", ")", ")", "\n", "}", "else", "{", "fields", "[", "key", "]", "=", "format", ".", "escapeFieldValue", "(", "v", ".", "(", "string", ")", ")", "\n", "}", "\n", "}", "\n\n", "measurementString", ":=", "format", ".", "escapeMeasurement", "(", "measurement", ".", "(", "string", ")", ")", "\n\n", "tagsString", ":=", "format", ".", "joinMap", "(", "tags", ")", "\n", "if", "len", "(", "tagsString", ")", ">", "0", "{", "// Only add comma between measurement and tags if tags are not empty.", "// See https://docs.influxdata.com/influxdb/v1.2/write_protocols/line_protocol_reference/", "tagsString", "=", "\"", "\"", "+", "tagsString", "\n", "}", "\n\n", "fieldsString", ":=", "format", ".", "joinMap", "(", "fields", ")", "\n\n", "line", ":=", "fmt", ".", "Sprintf", "(", "`%s%s %s %d`", ",", "measurementString", ",", "tagsString", ",", "fieldsString", ",", "timestamp", ")", "\n\n", "format", ".", "SetAppliedContent", "(", "msg", ",", "[", "]", "byte", "(", "line", ")", ")", "\n", "return", "nil", "\n", "}" ]
// ApplyFormatter updates the message payload
[ "ApplyFormatter", "updates", "the", "message", "payload" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/format/jsontoinflux10.go#L144-L207
142,546
trivago/gollum
core/modulator.go
Modulate
func (modulators ModulatorArray) Modulate(msg *Message) ModulateResult { action := ModulateResultContinue for _, modulator := range modulators { switch modRes := modulator.Modulate(msg); modRes { case ModulateResultDiscard, ModulateResultFallback: return modRes // ### return, break modulator calls ### } } return action }
go
func (modulators ModulatorArray) Modulate(msg *Message) ModulateResult { action := ModulateResultContinue for _, modulator := range modulators { switch modRes := modulator.Modulate(msg); modRes { case ModulateResultDiscard, ModulateResultFallback: return modRes // ### return, break modulator calls ### } } return action }
[ "func", "(", "modulators", "ModulatorArray", ")", "Modulate", "(", "msg", "*", "Message", ")", "ModulateResult", "{", "action", ":=", "ModulateResultContinue", "\n", "for", "_", ",", "modulator", ":=", "range", "modulators", "{", "switch", "modRes", ":=", "modulator", ".", "Modulate", "(", "msg", ")", ";", "modRes", "{", "case", "ModulateResultDiscard", ",", "ModulateResultFallback", ":", "return", "modRes", "// ### return, break modulator calls ###", "\n", "}", "\n", "}", "\n", "return", "action", "\n", "}" ]
// Modulate calls Modulate on every Modulator in the array and react according // to the definition of each ModulateResult state.
[ "Modulate", "calls", "Modulate", "on", "every", "Modulator", "in", "the", "array", "and", "react", "according", "to", "the", "definition", "of", "each", "ModulateResult", "state", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/modulator.go#L61-L70
142,547
trivago/gollum
producer/httprequest.go
sendReq
func (prod *HTTPRequest) sendReq(msg *core.Message) { var ( req *http.Request err error ) requestData := bytes.NewBuffer(msg.GetPayload()) if prod.rawPackets { // Assume the message already contains an HTTP request in wire format. // Create a Request object, override host, port and scheme, and send it out. req, err = http.ReadRequest(bufio.NewReader(requestData)) if req != nil { req.URL.Host = prod.destinationURL.Host req.URL.Scheme = prod.destinationURL.Scheme req.RequestURI = "" } } else { // Encapsulate the message in a POST request req, err = http.NewRequest("POST", prod.destinationURL.String(), requestData) if req != nil { req.Header.Add("Content-type", prod.encoding) } } if err != nil { prod.Logger.Error("Invalid request: ", err) prod.TryFallback(msg) prod.lastError = err return // ### return, malformed request ### } go func() { _, _, err := httpRequestWrapper(http.DefaultClient.Do(req)) prod.lastError = err if err != nil { // Fail prod.Logger.WithError(err).Error("Send failed") if !prod.isHostUp() { prod.Logger.Error("Host is down") } prod.TryFallback(msg) return } // Success // TBD: health check? (ex-fuse breaker) }() }
go
func (prod *HTTPRequest) sendReq(msg *core.Message) { var ( req *http.Request err error ) requestData := bytes.NewBuffer(msg.GetPayload()) if prod.rawPackets { // Assume the message already contains an HTTP request in wire format. // Create a Request object, override host, port and scheme, and send it out. req, err = http.ReadRequest(bufio.NewReader(requestData)) if req != nil { req.URL.Host = prod.destinationURL.Host req.URL.Scheme = prod.destinationURL.Scheme req.RequestURI = "" } } else { // Encapsulate the message in a POST request req, err = http.NewRequest("POST", prod.destinationURL.String(), requestData) if req != nil { req.Header.Add("Content-type", prod.encoding) } } if err != nil { prod.Logger.Error("Invalid request: ", err) prod.TryFallback(msg) prod.lastError = err return // ### return, malformed request ### } go func() { _, _, err := httpRequestWrapper(http.DefaultClient.Do(req)) prod.lastError = err if err != nil { // Fail prod.Logger.WithError(err).Error("Send failed") if !prod.isHostUp() { prod.Logger.Error("Host is down") } prod.TryFallback(msg) return } // Success // TBD: health check? (ex-fuse breaker) }() }
[ "func", "(", "prod", "*", "HTTPRequest", ")", "sendReq", "(", "msg", "*", "core", ".", "Message", ")", "{", "var", "(", "req", "*", "http", ".", "Request", "\n", "err", "error", "\n", ")", "\n\n", "requestData", ":=", "bytes", ".", "NewBuffer", "(", "msg", ".", "GetPayload", "(", ")", ")", "\n\n", "if", "prod", ".", "rawPackets", "{", "// Assume the message already contains an HTTP request in wire format.", "// Create a Request object, override host, port and scheme, and send it out.", "req", ",", "err", "=", "http", ".", "ReadRequest", "(", "bufio", ".", "NewReader", "(", "requestData", ")", ")", "\n", "if", "req", "!=", "nil", "{", "req", ".", "URL", ".", "Host", "=", "prod", ".", "destinationURL", ".", "Host", "\n", "req", ".", "URL", ".", "Scheme", "=", "prod", ".", "destinationURL", ".", "Scheme", "\n", "req", ".", "RequestURI", "=", "\"", "\"", "\n", "}", "\n", "}", "else", "{", "// Encapsulate the message in a POST request", "req", ",", "err", "=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "prod", ".", "destinationURL", ".", "String", "(", ")", ",", "requestData", ")", "\n", "if", "req", "!=", "nil", "{", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "prod", ".", "encoding", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "prod", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "prod", ".", "TryFallback", "(", "msg", ")", "\n", "prod", ".", "lastError", "=", "err", "\n", "return", "// ### return, malformed request ###", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "_", ",", "_", ",", "err", ":=", "httpRequestWrapper", "(", "http", ".", "DefaultClient", ".", "Do", "(", "req", ")", ")", "\n", "prod", ".", "lastError", "=", "err", "\n", "if", "err", "!=", "nil", "{", "// Fail", "prod", ".", "Logger", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "if", "!", "prod", ".", "isHostUp", "(", ")", "{", "prod", ".", "Logger", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "prod", ".", "TryFallback", "(", "msg", ")", "\n", "return", "\n", "}", "\n", "// Success", "// TBD: health check? (ex-fuse breaker)", "}", "(", ")", "\n", "}" ]
// The onMessage callback
[ "The", "onMessage", "callback" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/httprequest.go#L157-L204
142,548
trivago/gollum
core/version.go
GetVersionNumber
func GetVersionNumber() (int64, int) { ver := strings.Replace(GetVersionString(), "-", ".", -1) parts := strings.Split(ver, ".") multiplier := int64(100 * 100) // major, minor, patch version := int64(0) buildNum := int(0) for i, subVerString := range parts { if i == 3 { buildNum, _ = strconv.Atoi(subVerString) break // done } subVer, err := strconv.Atoi(subVerString) if err != nil { break // cannot parse } version += int64(subVer) * multiplier multiplier /= 100 } return version, buildNum }
go
func GetVersionNumber() (int64, int) { ver := strings.Replace(GetVersionString(), "-", ".", -1) parts := strings.Split(ver, ".") multiplier := int64(100 * 100) // major, minor, patch version := int64(0) buildNum := int(0) for i, subVerString := range parts { if i == 3 { buildNum, _ = strconv.Atoi(subVerString) break // done } subVer, err := strconv.Atoi(subVerString) if err != nil { break // cannot parse } version += int64(subVer) * multiplier multiplier /= 100 } return version, buildNum }
[ "func", "GetVersionNumber", "(", ")", "(", "int64", ",", "int", ")", "{", "ver", ":=", "strings", ".", "Replace", "(", "GetVersionString", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "parts", ":=", "strings", ".", "Split", "(", "ver", ",", "\"", "\"", ")", "\n", "multiplier", ":=", "int64", "(", "100", "*", "100", ")", "// major, minor, patch", "\n", "version", ":=", "int64", "(", "0", ")", "\n", "buildNum", ":=", "int", "(", "0", ")", "\n", "for", "i", ",", "subVerString", ":=", "range", "parts", "{", "if", "i", "==", "3", "{", "buildNum", ",", "_", "=", "strconv", ".", "Atoi", "(", "subVerString", ")", "\n", "break", "// done", "\n", "}", "\n", "subVer", ",", "err", ":=", "strconv", ".", "Atoi", "(", "subVerString", ")", "\n", "if", "err", "!=", "nil", "{", "break", "// cannot parse", "\n", "}", "\n", "version", "+=", "int64", "(", "subVer", ")", "*", "multiplier", "\n", "multiplier", "/=", "100", "\n\n", "}", "\n", "return", "version", ",", "buildNum", "\n", "}" ]
// GetVersionNumber returns the version as integer. Each part of the semver // string is assigned to decimals, so v1.2.3 will be 10203. // The build number refers to the first postfix of the semver string, i.e. // v1.2.3-4-badf00d will return 10203 and 4
[ "GetVersionNumber", "returns", "the", "version", "as", "integer", ".", "Each", "part", "of", "the", "semver", "string", "is", "assigned", "to", "decimals", "so", "v1", ".", "2", ".", "3", "will", "be", "10203", ".", "The", "build", "number", "refers", "to", "the", "first", "postfix", "of", "the", "semver", "string", "i", ".", "e", ".", "v1", ".", "2", ".", "3", "-", "4", "-", "badf00d", "will", "return", "10203", "and", "4" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/version.go#L36-L56
142,549
trivago/gollum
core/filtermodulator.go
Modulate
func (filterModulator *FilterModulator) Modulate(msg *Message) ModulateResult { result, err := filterModulator.ApplyFilter(msg) if err != nil { logrus.Warning("FilterModulator with error:", err) } if result == FilterResultMessageAccept { return ModulateResultContinue } newStreamID := result.GetStreamID() if newStreamID == InvalidStreamID { return ModulateResultDiscard } msg.SetStreamID(newStreamID) return ModulateResultFallback }
go
func (filterModulator *FilterModulator) Modulate(msg *Message) ModulateResult { result, err := filterModulator.ApplyFilter(msg) if err != nil { logrus.Warning("FilterModulator with error:", err) } if result == FilterResultMessageAccept { return ModulateResultContinue } newStreamID := result.GetStreamID() if newStreamID == InvalidStreamID { return ModulateResultDiscard } msg.SetStreamID(newStreamID) return ModulateResultFallback }
[ "func", "(", "filterModulator", "*", "FilterModulator", ")", "Modulate", "(", "msg", "*", "Message", ")", "ModulateResult", "{", "result", ",", "err", ":=", "filterModulator", ".", "ApplyFilter", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warning", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "result", "==", "FilterResultMessageAccept", "{", "return", "ModulateResultContinue", "\n", "}", "\n\n", "newStreamID", ":=", "result", ".", "GetStreamID", "(", ")", "\n", "if", "newStreamID", "==", "InvalidStreamID", "{", "return", "ModulateResultDiscard", "\n", "}", "\n\n", "msg", ".", "SetStreamID", "(", "newStreamID", ")", "\n", "return", "ModulateResultFallback", "\n", "}" ]
// Modulate implementation for Filters
[ "Modulate", "implementation", "for", "Filters" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/filtermodulator.go#L34-L51
142,550
trivago/gollum
docs/generator/plugindocument.go
next
func (iter *sliceIterator) next() (string, string, int) { if iter.position > len(iter.slice)-1 { return "", "", -1 } position := iter.position iter.position++ return iter.slice[position], strings.Trim(iter.slice[position], " \t"), position }
go
func (iter *sliceIterator) next() (string, string, int) { if iter.position > len(iter.slice)-1 { return "", "", -1 } position := iter.position iter.position++ return iter.slice[position], strings.Trim(iter.slice[position], " \t"), position }
[ "func", "(", "iter", "*", "sliceIterator", ")", "next", "(", ")", "(", "string", ",", "string", ",", "int", ")", "{", "if", "iter", ".", "position", ">", "len", "(", "iter", ".", "slice", ")", "-", "1", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "-", "1", "\n", "}", "\n", "position", ":=", "iter", ".", "position", "\n", "iter", ".", "position", "++", "\n", "return", "iter", ".", "slice", "[", "position", "]", ",", "strings", ".", "Trim", "(", "iter", ".", "slice", "[", "position", "]", ",", "\"", "\\t", "\"", ")", ",", "position", "\n", "}" ]
// next returns the current string and advances the iterator
[ "next", "returns", "the", "current", "string", "and", "advances", "the", "iterator" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/plugindocument.go#L47-L54
142,551
trivago/gollum
docs/generator/plugindocument.go
NewPluginDocument
func NewPluginDocument(plugin GollumPlugin) PluginDocument { pluginDocument := PluginDocument{ PackageName: plugin.Pkg, PluginName: plugin.Name, } // The "Enable" parameter is implemented in the coordinator / plugonconfig // and not inherited from simple*** types. Documentation for this option is // hardcoded here, becacuse inheriting from the simple*** types is voluntary, // and it would be counterproductive to contrive support in the RST generaotor // just for fishing this parameter from the core. switch plugin.Pkg { case "consumer", "producer", "router": pluginDocument.Parameters.add(&Definition{ name: "Enable", desc: "Switches this plugin on or off.", dfl: "true", }) } // Parse the comment string pluginDocument.ParseString(plugin.Comment) // Set Param values from struct tags for _, stParamDef := range plugin.StructTagParams.slice { if docParamDef, found := pluginDocument.Parameters.findByName(stParamDef.name); found { // Parameter is already documented, add values from struct tags docParamDef.unit = stParamDef.unit docParamDef.dfl = stParamDef.dfl } else { // Undocumented parameter pluginDocument.Parameters.add(stParamDef) } } // - Recursively generate PluginDocuments for all embedded types (SimpleProducer etc.) // with embedTag in this plugin's embed declaration // - Include their parameter lists in this doc // - Include their metadata lists in this doc for _, embed := range plugin.Embeds { importDir := getImportDir(embed.pkg) astPackage := parseSourcePath(importDir) for _, embedPugin := range findGollumPlugins(astPackage) { if embedPugin.Pkg == embed.pkg && embedPugin.Name == embed.name { // Recursion doc := NewPluginDocument(embedPugin) pluginDocument.InheritParameters(doc) pluginDocument.InheritMetadata(doc) } } } return pluginDocument }
go
func NewPluginDocument(plugin GollumPlugin) PluginDocument { pluginDocument := PluginDocument{ PackageName: plugin.Pkg, PluginName: plugin.Name, } // The "Enable" parameter is implemented in the coordinator / plugonconfig // and not inherited from simple*** types. Documentation for this option is // hardcoded here, becacuse inheriting from the simple*** types is voluntary, // and it would be counterproductive to contrive support in the RST generaotor // just for fishing this parameter from the core. switch plugin.Pkg { case "consumer", "producer", "router": pluginDocument.Parameters.add(&Definition{ name: "Enable", desc: "Switches this plugin on or off.", dfl: "true", }) } // Parse the comment string pluginDocument.ParseString(plugin.Comment) // Set Param values from struct tags for _, stParamDef := range plugin.StructTagParams.slice { if docParamDef, found := pluginDocument.Parameters.findByName(stParamDef.name); found { // Parameter is already documented, add values from struct tags docParamDef.unit = stParamDef.unit docParamDef.dfl = stParamDef.dfl } else { // Undocumented parameter pluginDocument.Parameters.add(stParamDef) } } // - Recursively generate PluginDocuments for all embedded types (SimpleProducer etc.) // with embedTag in this plugin's embed declaration // - Include their parameter lists in this doc // - Include their metadata lists in this doc for _, embed := range plugin.Embeds { importDir := getImportDir(embed.pkg) astPackage := parseSourcePath(importDir) for _, embedPugin := range findGollumPlugins(astPackage) { if embedPugin.Pkg == embed.pkg && embedPugin.Name == embed.name { // Recursion doc := NewPluginDocument(embedPugin) pluginDocument.InheritParameters(doc) pluginDocument.InheritMetadata(doc) } } } return pluginDocument }
[ "func", "NewPluginDocument", "(", "plugin", "GollumPlugin", ")", "PluginDocument", "{", "pluginDocument", ":=", "PluginDocument", "{", "PackageName", ":", "plugin", ".", "Pkg", ",", "PluginName", ":", "plugin", ".", "Name", ",", "}", "\n\n", "// The \"Enable\" parameter is implemented in the coordinator / plugonconfig", "// and not inherited from simple*** types. Documentation for this option is", "// hardcoded here, becacuse inheriting from the simple*** types is voluntary,", "// and it would be counterproductive to contrive support in the RST generaotor", "// just for fishing this parameter from the core.", "switch", "plugin", ".", "Pkg", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "pluginDocument", ".", "Parameters", ".", "add", "(", "&", "Definition", "{", "name", ":", "\"", "\"", ",", "desc", ":", "\"", "\"", ",", "dfl", ":", "\"", "\"", ",", "}", ")", "\n", "}", "\n\n", "// Parse the comment string", "pluginDocument", ".", "ParseString", "(", "plugin", ".", "Comment", ")", "\n\n", "// Set Param values from struct tags", "for", "_", ",", "stParamDef", ":=", "range", "plugin", ".", "StructTagParams", ".", "slice", "{", "if", "docParamDef", ",", "found", ":=", "pluginDocument", ".", "Parameters", ".", "findByName", "(", "stParamDef", ".", "name", ")", ";", "found", "{", "// Parameter is already documented, add values from struct tags", "docParamDef", ".", "unit", "=", "stParamDef", ".", "unit", "\n", "docParamDef", ".", "dfl", "=", "stParamDef", ".", "dfl", "\n\n", "}", "else", "{", "// Undocumented parameter", "pluginDocument", ".", "Parameters", ".", "add", "(", "stParamDef", ")", "\n", "}", "\n", "}", "\n\n", "// - Recursively generate PluginDocuments for all embedded types (SimpleProducer etc.)", "// with embedTag in this plugin's embed declaration", "// - Include their parameter lists in this doc", "// - Include their metadata lists in this doc", "for", "_", ",", "embed", ":=", "range", "plugin", ".", "Embeds", "{", "importDir", ":=", "getImportDir", "(", "embed", ".", "pkg", ")", "\n", "astPackage", ":=", "parseSourcePath", "(", "importDir", ")", "\n", "for", "_", ",", "embedPugin", ":=", "range", "findGollumPlugins", "(", "astPackage", ")", "{", "if", "embedPugin", ".", "Pkg", "==", "embed", ".", "pkg", "&&", "embedPugin", ".", "Name", "==", "embed", ".", "name", "{", "// Recursion", "doc", ":=", "NewPluginDocument", "(", "embedPugin", ")", "\n", "pluginDocument", ".", "InheritParameters", "(", "doc", ")", "\n", "pluginDocument", ".", "InheritMetadata", "(", "doc", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "pluginDocument", "\n", "}" ]
// NewPluginDocument creates a PluginDocument from the GollumPlugin
[ "NewPluginDocument", "creates", "a", "PluginDocument", "from", "the", "GollumPlugin" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/plugindocument.go#L68-L123
142,552
trivago/gollum
docs/generator/plugindocument.go
DumpString
func (doc *PluginDocument) DumpString() string { str := "" str += "==================== START DUMP ============================\n" str += "PackageName: [" + doc.PackageName + "]\n" str += "PluginName: [" + doc.PluginName + "]\n" str += "BlockHeading: [" + doc.BlockHeading + "]\n" str += "Description: [" + doc.Description + "]\n\n" str += "Parameters: [" + "\n" str += doc.Parameters.dumpString() + "\n" str += "]\n\n" for parentName, defMap := range doc.InheritedParameters { str += "Parameters (from " + parentName + ")[\n" str += defMap.dumpString() + "\n" str += "]\n\n" } str += "Metadata: [" + "\n" str += doc.Metadata.dumpString() + "\n" for parentName, defMap := range doc.InheritedMetadata { str += "Metadata (from " + parentName + ")[\n" str += defMap.dumpString() + "\n" str += "]\n\n" } str += "Example: [" + "\n------------\n" + doc.Example + "\n----------]\n" str += "==================== END DUMP ============================\n" return str }
go
func (doc *PluginDocument) DumpString() string { str := "" str += "==================== START DUMP ============================\n" str += "PackageName: [" + doc.PackageName + "]\n" str += "PluginName: [" + doc.PluginName + "]\n" str += "BlockHeading: [" + doc.BlockHeading + "]\n" str += "Description: [" + doc.Description + "]\n\n" str += "Parameters: [" + "\n" str += doc.Parameters.dumpString() + "\n" str += "]\n\n" for parentName, defMap := range doc.InheritedParameters { str += "Parameters (from " + parentName + ")[\n" str += defMap.dumpString() + "\n" str += "]\n\n" } str += "Metadata: [" + "\n" str += doc.Metadata.dumpString() + "\n" for parentName, defMap := range doc.InheritedMetadata { str += "Metadata (from " + parentName + ")[\n" str += defMap.dumpString() + "\n" str += "]\n\n" } str += "Example: [" + "\n------------\n" + doc.Example + "\n----------]\n" str += "==================== END DUMP ============================\n" return str }
[ "func", "(", "doc", "*", "PluginDocument", ")", "DumpString", "(", ")", "string", "{", "str", ":=", "\"", "\"", "\n", "str", "+=", "\"", "\\n", "\"", "\n", "str", "+=", "\"", "\"", "+", "doc", ".", "PackageName", "+", "\"", "\\n", "\"", "\n", "str", "+=", "\"", "\"", "+", "doc", ".", "PluginName", "+", "\"", "\\n", "\"", "\n", "str", "+=", "\"", "\"", "+", "doc", ".", "BlockHeading", "+", "\"", "\\n", "\"", "\n", "str", "+=", "\"", "\"", "+", "doc", ".", "Description", "+", "\"", "\\n", "\\n", "\"", "\n", "str", "+=", "\"", "\"", "+", "\"", "\\n", "\"", "\n", "str", "+=", "doc", ".", "Parameters", ".", "dumpString", "(", ")", "+", "\"", "\\n", "\"", "\n", "str", "+=", "\"", "\\n", "\\n", "\"", "\n", "for", "parentName", ",", "defMap", ":=", "range", "doc", ".", "InheritedParameters", "{", "str", "+=", "\"", "\"", "+", "parentName", "+", "\"", "\\n", "\"", "\n", "str", "+=", "defMap", ".", "dumpString", "(", ")", "+", "\"", "\\n", "\"", "\n", "str", "+=", "\"", "\\n", "\\n", "\"", "\n", "}", "\n", "str", "+=", "\"", "\"", "+", "\"", "\\n", "\"", "\n", "str", "+=", "doc", ".", "Metadata", ".", "dumpString", "(", ")", "+", "\"", "\\n", "\"", "\n", "for", "parentName", ",", "defMap", ":=", "range", "doc", ".", "InheritedMetadata", "{", "str", "+=", "\"", "\"", "+", "parentName", "+", "\"", "\\n", "\"", "\n", "str", "+=", "defMap", ".", "dumpString", "(", ")", "+", "\"", "\\n", "\"", "\n", "str", "+=", "\"", "\\n", "\\n", "\"", "\n", "}", "\n", "str", "+=", "\"", "\"", "+", "\"", "\\n", "\\n", "\"", "+", "doc", ".", "Example", "+", "\"", "\\n", "\\n", "\"", "\n", "str", "+=", "\"", "\\n", "\"", "\n", "return", "str", "\n", "}" ]
// DumpString returns a human-readable string dumpString of this object
[ "DumpString", "returns", "a", "human", "-", "readable", "string", "dumpString", "of", "this", "object" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/plugindocument.go#L126-L151
142,553
trivago/gollum
docs/generator/plugindocument.go
InheritMetadata
func (doc *PluginDocument) InheritMetadata(parentDoc PluginDocument) { if doc.InheritedMetadata == nil { doc.InheritedMetadata = make(map[string]DefinitionList) } // Inherit the parent's direct metadata fields, but exclude locally defined params doc.InheritedMetadata[parentDoc.PackageName+"."+parentDoc.PluginName] = parentDoc.Metadata.subtractList(doc.Metadata) // Inherit the parent's inherited metadata fields, but exclude locally defined params for parentName, metadataSet := range parentDoc.InheritedMetadata { doc.InheritedMetadata[parentName] = metadataSet.subtractList(doc.Metadata) } }
go
func (doc *PluginDocument) InheritMetadata(parentDoc PluginDocument) { if doc.InheritedMetadata == nil { doc.InheritedMetadata = make(map[string]DefinitionList) } // Inherit the parent's direct metadata fields, but exclude locally defined params doc.InheritedMetadata[parentDoc.PackageName+"."+parentDoc.PluginName] = parentDoc.Metadata.subtractList(doc.Metadata) // Inherit the parent's inherited metadata fields, but exclude locally defined params for parentName, metadataSet := range parentDoc.InheritedMetadata { doc.InheritedMetadata[parentName] = metadataSet.subtractList(doc.Metadata) } }
[ "func", "(", "doc", "*", "PluginDocument", ")", "InheritMetadata", "(", "parentDoc", "PluginDocument", ")", "{", "if", "doc", ".", "InheritedMetadata", "==", "nil", "{", "doc", ".", "InheritedMetadata", "=", "make", "(", "map", "[", "string", "]", "DefinitionList", ")", "\n", "}", "\n\n", "// Inherit the parent's direct metadata fields, but exclude locally defined params", "doc", ".", "InheritedMetadata", "[", "parentDoc", ".", "PackageName", "+", "\"", "\"", "+", "parentDoc", ".", "PluginName", "]", "=", "parentDoc", ".", "Metadata", ".", "subtractList", "(", "doc", ".", "Metadata", ")", "\n\n", "// Inherit the parent's inherited metadata fields, but exclude locally defined params", "for", "parentName", ",", "metadataSet", ":=", "range", "parentDoc", ".", "InheritedMetadata", "{", "doc", ".", "InheritedMetadata", "[", "parentName", "]", "=", "metadataSet", ".", "subtractList", "(", "doc", ".", "Metadata", ")", "\n", "}", "\n", "}" ]
// InheritMetadata imports the .Metadata property of `document` into this document's // inherited metadata list
[ "InheritMetadata", "imports", "the", ".", "Metadata", "property", "of", "document", "into", "this", "document", "s", "inherited", "metadata", "list" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/plugindocument.go#L242-L255
142,554
trivago/gollum
docs/generator/plugindocument.go
InheritParameters
func (doc *PluginDocument) InheritParameters(parentDoc PluginDocument) { if doc.InheritedParameters == nil { doc.InheritedParameters = make(map[string]DefinitionList) } // Inherit the parent's direct parameters, but exclude locally defined params doc.InheritedParameters[parentDoc.PackageName+"."+parentDoc.PluginName] = parentDoc.Parameters.subtractList(doc.Parameters) // Inherit the parent's inherited params, but exclude locally defined params for parentName, paramSet := range parentDoc.InheritedParameters { doc.InheritedParameters[parentName] = paramSet.subtractList(doc.Parameters) } }
go
func (doc *PluginDocument) InheritParameters(parentDoc PluginDocument) { if doc.InheritedParameters == nil { doc.InheritedParameters = make(map[string]DefinitionList) } // Inherit the parent's direct parameters, but exclude locally defined params doc.InheritedParameters[parentDoc.PackageName+"."+parentDoc.PluginName] = parentDoc.Parameters.subtractList(doc.Parameters) // Inherit the parent's inherited params, but exclude locally defined params for parentName, paramSet := range parentDoc.InheritedParameters { doc.InheritedParameters[parentName] = paramSet.subtractList(doc.Parameters) } }
[ "func", "(", "doc", "*", "PluginDocument", ")", "InheritParameters", "(", "parentDoc", "PluginDocument", ")", "{", "if", "doc", ".", "InheritedParameters", "==", "nil", "{", "doc", ".", "InheritedParameters", "=", "make", "(", "map", "[", "string", "]", "DefinitionList", ")", "\n", "}", "\n\n", "// Inherit the parent's direct parameters, but exclude locally defined params", "doc", ".", "InheritedParameters", "[", "parentDoc", ".", "PackageName", "+", "\"", "\"", "+", "parentDoc", ".", "PluginName", "]", "=", "parentDoc", ".", "Parameters", ".", "subtractList", "(", "doc", ".", "Parameters", ")", "\n\n", "// Inherit the parent's inherited params, but exclude locally defined params", "for", "parentName", ",", "paramSet", ":=", "range", "parentDoc", ".", "InheritedParameters", "{", "doc", ".", "InheritedParameters", "[", "parentName", "]", "=", "paramSet", ".", "subtractList", "(", "doc", ".", "Parameters", ")", "\n", "}", "\n", "}" ]
// InheritParameters imports the .Parameters property of `document` into this document's // inherited param list
[ "InheritParameters", "imports", "the", ".", "Parameters", "property", "of", "document", "into", "this", "document", "s", "inherited", "param", "list" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/plugindocument.go#L259-L272
142,555
trivago/gollum
docs/generator/plugindocument.go
GetRST
func (doc PluginDocument) GetRST() string { result := "" // Print top comment result += ".. Autogenerated by Gollum RST generator (docs/generator/*.go)\n\n" // Print heading result += doc.PluginName + "\n" result += strings.Repeat("=", len(doc.PluginName)) + "\n" // Print description result += "\n" result += docBulletsToRstBullets(doc.Description) + "\n" result += "\n" // Print native metadata if len(doc.Metadata.slice) > 0 { result += formatRstHeading("Metadata") result += doc.Metadata.getRST(false, 0) } // Print inherited metadata for _, parentName := range sortInheritedKeys(doc.InheritedMetadata) { if len(doc.InheritedMetadata[parentName].slice) == 0 { // Skip title for empty sets continue } result += formatRstHeading( "Metadata (from " + /* strings.TrimPrefix(*/ parentName /*, "core.") */ + ")") result += doc.InheritedMetadata[parentName].getRST(false, 0) } // Print native parameters if len(doc.Parameters.slice) > 0 { result += formatRstHeading("Parameters") result += doc.Parameters.getRST(true, 0) } // Print inherited parameters for _, parentName := range sortInheritedKeys(doc.InheritedParameters) { if len(doc.InheritedParameters[parentName].slice) == 0 { // Skip title for empty param sets continue } result += formatRstHeading( "Parameters (from " + /* strings.TrimPrefix(*/ parentName /*, "core.") */ + ")") result += doc.InheritedParameters[parentName].getRST(true, 0) } // Print config example if len(doc.Example) > 0 { result += formatRstHeading("Examples") codeBlock := false for _, line := range strings.Split(doc.Example, "\n") { if strings.Index(line, " ") == 0 { if !codeBlock { result += ".. code-block:: yaml\n\n" codeBlock = true } } else { if codeBlock { result += "\n" codeBlock = false } } if codeBlock { result += "\t" + line + "\n" } else { result += line + "\n" } } } return result }
go
func (doc PluginDocument) GetRST() string { result := "" // Print top comment result += ".. Autogenerated by Gollum RST generator (docs/generator/*.go)\n\n" // Print heading result += doc.PluginName + "\n" result += strings.Repeat("=", len(doc.PluginName)) + "\n" // Print description result += "\n" result += docBulletsToRstBullets(doc.Description) + "\n" result += "\n" // Print native metadata if len(doc.Metadata.slice) > 0 { result += formatRstHeading("Metadata") result += doc.Metadata.getRST(false, 0) } // Print inherited metadata for _, parentName := range sortInheritedKeys(doc.InheritedMetadata) { if len(doc.InheritedMetadata[parentName].slice) == 0 { // Skip title for empty sets continue } result += formatRstHeading( "Metadata (from " + /* strings.TrimPrefix(*/ parentName /*, "core.") */ + ")") result += doc.InheritedMetadata[parentName].getRST(false, 0) } // Print native parameters if len(doc.Parameters.slice) > 0 { result += formatRstHeading("Parameters") result += doc.Parameters.getRST(true, 0) } // Print inherited parameters for _, parentName := range sortInheritedKeys(doc.InheritedParameters) { if len(doc.InheritedParameters[parentName].slice) == 0 { // Skip title for empty param sets continue } result += formatRstHeading( "Parameters (from " + /* strings.TrimPrefix(*/ parentName /*, "core.") */ + ")") result += doc.InheritedParameters[parentName].getRST(true, 0) } // Print config example if len(doc.Example) > 0 { result += formatRstHeading("Examples") codeBlock := false for _, line := range strings.Split(doc.Example, "\n") { if strings.Index(line, " ") == 0 { if !codeBlock { result += ".. code-block:: yaml\n\n" codeBlock = true } } else { if codeBlock { result += "\n" codeBlock = false } } if codeBlock { result += "\t" + line + "\n" } else { result += line + "\n" } } } return result }
[ "func", "(", "doc", "PluginDocument", ")", "GetRST", "(", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "// Print top comment", "result", "+=", "\"", "\\n", "\\n", "\"", "\n\n", "// Print heading", "result", "+=", "doc", ".", "PluginName", "+", "\"", "\\n", "\"", "\n", "result", "+=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "len", "(", "doc", ".", "PluginName", ")", ")", "+", "\"", "\\n", "\"", "\n\n", "// Print description", "result", "+=", "\"", "\\n", "\"", "\n", "result", "+=", "docBulletsToRstBullets", "(", "doc", ".", "Description", ")", "+", "\"", "\\n", "\"", "\n", "result", "+=", "\"", "\\n", "\"", "\n\n", "// Print native metadata", "if", "len", "(", "doc", ".", "Metadata", ".", "slice", ")", ">", "0", "{", "result", "+=", "formatRstHeading", "(", "\"", "\"", ")", "\n", "result", "+=", "doc", ".", "Metadata", ".", "getRST", "(", "false", ",", "0", ")", "\n", "}", "\n\n", "// Print inherited metadata", "for", "_", ",", "parentName", ":=", "range", "sortInheritedKeys", "(", "doc", ".", "InheritedMetadata", ")", "{", "if", "len", "(", "doc", ".", "InheritedMetadata", "[", "parentName", "]", ".", "slice", ")", "==", "0", "{", "// Skip title for empty sets", "continue", "\n", "}", "\n", "result", "+=", "formatRstHeading", "(", "\"", "\"", "+", "/* strings.TrimPrefix(*/", "parentName", "/*, \"core.\") */", "+", "\"", "\"", ")", "\n\n", "result", "+=", "doc", ".", "InheritedMetadata", "[", "parentName", "]", ".", "getRST", "(", "false", ",", "0", ")", "\n", "}", "\n\n", "// Print native parameters", "if", "len", "(", "doc", ".", "Parameters", ".", "slice", ")", ">", "0", "{", "result", "+=", "formatRstHeading", "(", "\"", "\"", ")", "\n", "result", "+=", "doc", ".", "Parameters", ".", "getRST", "(", "true", ",", "0", ")", "\n", "}", "\n\n", "// Print inherited parameters", "for", "_", ",", "parentName", ":=", "range", "sortInheritedKeys", "(", "doc", ".", "InheritedParameters", ")", "{", "if", "len", "(", "doc", ".", "InheritedParameters", "[", "parentName", "]", ".", "slice", ")", "==", "0", "{", "// Skip title for empty param sets", "continue", "\n", "}", "\n", "result", "+=", "formatRstHeading", "(", "\"", "\"", "+", "/* strings.TrimPrefix(*/", "parentName", "/*, \"core.\") */", "+", "\"", "\"", ")", "\n", "result", "+=", "doc", ".", "InheritedParameters", "[", "parentName", "]", ".", "getRST", "(", "true", ",", "0", ")", "\n", "}", "\n\n", "// Print config example", "if", "len", "(", "doc", ".", "Example", ")", ">", "0", "{", "result", "+=", "formatRstHeading", "(", "\"", "\"", ")", "\n", "codeBlock", ":=", "false", "\n\n", "for", "_", ",", "line", ":=", "range", "strings", ".", "Split", "(", "doc", ".", "Example", ",", "\"", "\\n", "\"", ")", "{", "if", "strings", ".", "Index", "(", "line", ",", "\"", "\"", ")", "==", "0", "{", "if", "!", "codeBlock", "{", "result", "+=", "\"", "\\n", "\\n", "\"", "\n", "codeBlock", "=", "true", "\n", "}", "\n", "}", "else", "{", "if", "codeBlock", "{", "result", "+=", "\"", "\\n", "\"", "\n", "codeBlock", "=", "false", "\n", "}", "\n", "}", "\n\n", "if", "codeBlock", "{", "result", "+=", "\"", "\\t", "\"", "+", "line", "+", "\"", "\\n", "\"", "\n", "}", "else", "{", "result", "+=", "line", "+", "\"", "\\n", "\"", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// GetRST returns an RST representation of this PluginDocument.
[ "GetRST", "returns", "an", "RST", "representation", "of", "this", "PluginDocument", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/plugindocument.go#L309-L387
142,556
trivago/gollum
core/metrics.go
GetStreamMetric
func GetStreamMetric(streamID MessageStreamID) *StreamMetric { metricsStreamRegistryGuard.RLock() if stream, ok := metricsStreamRegistry[streamID]; ok { metricsStreamRegistryGuard.RUnlock() return stream } metricsStreamRegistryGuard.RUnlock() metricsStreamRegistryGuard.Lock() defer metricsStreamRegistryGuard.Unlock() stream := &StreamMetric{ registry: NewMetricsRegistry(streamID.GetName()), Routed: metrics.NewCounter(), Discarded: metrics.NewCounter(), } stream.registry.Register("routed", stream.Routed) stream.registry.Register("discarded", stream.Discarded) metricsStreamRegistry[streamID] = stream return stream }
go
func GetStreamMetric(streamID MessageStreamID) *StreamMetric { metricsStreamRegistryGuard.RLock() if stream, ok := metricsStreamRegistry[streamID]; ok { metricsStreamRegistryGuard.RUnlock() return stream } metricsStreamRegistryGuard.RUnlock() metricsStreamRegistryGuard.Lock() defer metricsStreamRegistryGuard.Unlock() stream := &StreamMetric{ registry: NewMetricsRegistry(streamID.GetName()), Routed: metrics.NewCounter(), Discarded: metrics.NewCounter(), } stream.registry.Register("routed", stream.Routed) stream.registry.Register("discarded", stream.Discarded) metricsStreamRegistry[streamID] = stream return stream }
[ "func", "GetStreamMetric", "(", "streamID", "MessageStreamID", ")", "*", "StreamMetric", "{", "metricsStreamRegistryGuard", ".", "RLock", "(", ")", "\n", "if", "stream", ",", "ok", ":=", "metricsStreamRegistry", "[", "streamID", "]", ";", "ok", "{", "metricsStreamRegistryGuard", ".", "RUnlock", "(", ")", "\n", "return", "stream", "\n", "}", "\n", "metricsStreamRegistryGuard", ".", "RUnlock", "(", ")", "\n\n", "metricsStreamRegistryGuard", ".", "Lock", "(", ")", "\n", "defer", "metricsStreamRegistryGuard", ".", "Unlock", "(", ")", "\n\n", "stream", ":=", "&", "StreamMetric", "{", "registry", ":", "NewMetricsRegistry", "(", "streamID", ".", "GetName", "(", ")", ")", ",", "Routed", ":", "metrics", ".", "NewCounter", "(", ")", ",", "Discarded", ":", "metrics", ".", "NewCounter", "(", ")", ",", "}", "\n\n", "stream", ".", "registry", ".", "Register", "(", "\"", "\"", ",", "stream", ".", "Routed", ")", "\n", "stream", ".", "registry", ".", "Register", "(", "\"", "\"", ",", "stream", ".", "Discarded", ")", "\n", "metricsStreamRegistry", "[", "streamID", "]", "=", "stream", "\n\n", "return", "stream", "\n", "}" ]
// GetStreamMetric returns the metrics handles for a given stream.
[ "GetStreamMetric", "returns", "the", "metrics", "handles", "for", "a", "given", "stream", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metrics.go#L139-L161
142,557
trivago/gollum
core/router.go
Route
func Route(msg *Message, router Router) error { if router == nil { DiscardMessage(msg, "nil", fmt.Sprintf("Router for stream %s is nil", msg.GetStreamID().GetName())) return nil } action := router.Modulate(msg) streamName := msg.GetStreamID().GetName() switch action { case ModulateResultDiscard: MetricMessagesDiscarded.Inc(1) DiscardMessage(msg, router.GetID(), "Router discarded") return nil case ModulateResultContinue: MetricMessagesRouted.Inc(1) GetStreamMetric(msg.streamID).Routed.Inc(1) MessageTrace(msg, router.GetID(), "Routed") return router.Enqueue(msg) case ModulateResultFallback: if msg.GetStreamID() == router.GetStreamID() { prevStreamName := StreamRegistry.GetStreamName(msg.GetPrevStreamID()) return NewModulateResultError("Routing loop detected for router %s (from %s)", streamName, prevStreamName) } // Do NOT route the original message in this case. // If a modulate pipeline returns fallback, the message might have been // modified already. To meet expectations the CHANGED message has to be // routed. return Route(msg, msg.GetRouter()) } return NewModulateResultError("Unknown ModulateResult action: %d", action) }
go
func Route(msg *Message, router Router) error { if router == nil { DiscardMessage(msg, "nil", fmt.Sprintf("Router for stream %s is nil", msg.GetStreamID().GetName())) return nil } action := router.Modulate(msg) streamName := msg.GetStreamID().GetName() switch action { case ModulateResultDiscard: MetricMessagesDiscarded.Inc(1) DiscardMessage(msg, router.GetID(), "Router discarded") return nil case ModulateResultContinue: MetricMessagesRouted.Inc(1) GetStreamMetric(msg.streamID).Routed.Inc(1) MessageTrace(msg, router.GetID(), "Routed") return router.Enqueue(msg) case ModulateResultFallback: if msg.GetStreamID() == router.GetStreamID() { prevStreamName := StreamRegistry.GetStreamName(msg.GetPrevStreamID()) return NewModulateResultError("Routing loop detected for router %s (from %s)", streamName, prevStreamName) } // Do NOT route the original message in this case. // If a modulate pipeline returns fallback, the message might have been // modified already. To meet expectations the CHANGED message has to be // routed. return Route(msg, msg.GetRouter()) } return NewModulateResultError("Unknown ModulateResult action: %d", action) }
[ "func", "Route", "(", "msg", "*", "Message", ",", "router", "Router", ")", "error", "{", "if", "router", "==", "nil", "{", "DiscardMessage", "(", "msg", ",", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "GetStreamID", "(", ")", ".", "GetName", "(", ")", ")", ")", "\n", "return", "nil", "\n", "}", "\n\n", "action", ":=", "router", ".", "Modulate", "(", "msg", ")", "\n", "streamName", ":=", "msg", ".", "GetStreamID", "(", ")", ".", "GetName", "(", ")", "\n\n", "switch", "action", "{", "case", "ModulateResultDiscard", ":", "MetricMessagesDiscarded", ".", "Inc", "(", "1", ")", "\n", "DiscardMessage", "(", "msg", ",", "router", ".", "GetID", "(", ")", ",", "\"", "\"", ")", "\n", "return", "nil", "\n\n", "case", "ModulateResultContinue", ":", "MetricMessagesRouted", ".", "Inc", "(", "1", ")", "\n", "GetStreamMetric", "(", "msg", ".", "streamID", ")", ".", "Routed", ".", "Inc", "(", "1", ")", "\n", "MessageTrace", "(", "msg", ",", "router", ".", "GetID", "(", ")", ",", "\"", "\"", ")", "\n\n", "return", "router", ".", "Enqueue", "(", "msg", ")", "\n\n", "case", "ModulateResultFallback", ":", "if", "msg", ".", "GetStreamID", "(", ")", "==", "router", ".", "GetStreamID", "(", ")", "{", "prevStreamName", ":=", "StreamRegistry", ".", "GetStreamName", "(", "msg", ".", "GetPrevStreamID", "(", ")", ")", "\n", "return", "NewModulateResultError", "(", "\"", "\"", ",", "streamName", ",", "prevStreamName", ")", "\n", "}", "\n\n", "// Do NOT route the original message in this case.", "// If a modulate pipeline returns fallback, the message might have been", "// modified already. To meet expectations the CHANGED message has to be", "// routed.", "return", "Route", "(", "msg", ",", "msg", ".", "GetRouter", "(", ")", ")", "\n", "}", "\n\n", "return", "NewModulateResultError", "(", "\"", "\"", ",", "action", ")", "\n", "}" ]
// Route tries to enqueue a message to the given stream. This function also // handles redirections enforced by formatters.
[ "Route", "tries", "to", "enqueue", "a", "message", "to", "the", "given", "stream", ".", "This", "function", "also", "handles", "redirections", "enforced", "by", "formatters", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/router.go#L50-L88
142,558
trivago/gollum
core/router.go
RouteOriginal
func RouteOriginal(msg *Message, router Router) error { return Route(msg.CloneOriginal(), router) }
go
func RouteOriginal(msg *Message, router Router) error { return Route(msg.CloneOriginal(), router) }
[ "func", "RouteOriginal", "(", "msg", "*", "Message", ",", "router", "Router", ")", "error", "{", "return", "Route", "(", "msg", ".", "CloneOriginal", "(", ")", ",", "router", ")", "\n", "}" ]
// RouteOriginal restores the original message and routes it by using a // a given router.
[ "RouteOriginal", "restores", "the", "original", "message", "and", "routes", "it", "by", "using", "a", "a", "given", "router", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/router.go#L92-L94
142,559
trivago/gollum
core/router.go
DiscardMessage
func DiscardMessage(msg *Message, pluginID string, comment string) { GetStreamMetric(msg.GetStreamID()).Discarded.Inc(1) MessageTrace(msg, pluginID, comment) }
go
func DiscardMessage(msg *Message, pluginID string, comment string) { GetStreamMetric(msg.GetStreamID()).Discarded.Inc(1) MessageTrace(msg, pluginID, comment) }
[ "func", "DiscardMessage", "(", "msg", "*", "Message", ",", "pluginID", "string", ",", "comment", "string", ")", "{", "GetStreamMetric", "(", "msg", ".", "GetStreamID", "(", ")", ")", ".", "Discarded", ".", "Inc", "(", "1", ")", "\n", "MessageTrace", "(", "msg", ",", "pluginID", ",", "comment", ")", "\n", "}" ]
// DiscardMessage increases the discard statistic and discards the given // message.
[ "DiscardMessage", "increases", "the", "discard", "statistic", "and", "discards", "the", "given", "message", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/router.go#L98-L101
142,560
trivago/gollum
core/batchedproducer.go
appendMessage
func (prod *BatchedProducer) appendMessage(msg *Message) { prod.Batch.AppendOrFlush(msg, prod.flushBatch, prod.IsActiveOrStopping, prod.TryFallback) }
go
func (prod *BatchedProducer) appendMessage(msg *Message) { prod.Batch.AppendOrFlush(msg, prod.flushBatch, prod.IsActiveOrStopping, prod.TryFallback) }
[ "func", "(", "prod", "*", "BatchedProducer", ")", "appendMessage", "(", "msg", "*", "Message", ")", "{", "prod", ".", "Batch", ".", "AppendOrFlush", "(", "msg", ",", "prod", ".", "flushBatch", ",", "prod", ".", "IsActiveOrStopping", ",", "prod", ".", "TryFallback", ")", "\n", "}" ]
// appendMessage append a message to the batch at enqueuing
[ "appendMessage", "append", "a", "message", "to", "the", "batch", "at", "enqueuing" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/batchedproducer.go#L84-L86
142,561
trivago/gollum
core/batchedproducer.go
flushBatchOnTimeOut
func (prod *BatchedProducer) flushBatchOnTimeOut() { if prod.Batch.ReachedTimeThreshold(prod.batchTimeout) || prod.Batch.ReachedSizeThreshold(prod.batchFlushCount) { prod.flushBatch() } }
go
func (prod *BatchedProducer) flushBatchOnTimeOut() { if prod.Batch.ReachedTimeThreshold(prod.batchTimeout) || prod.Batch.ReachedSizeThreshold(prod.batchFlushCount) { prod.flushBatch() } }
[ "func", "(", "prod", "*", "BatchedProducer", ")", "flushBatchOnTimeOut", "(", ")", "{", "if", "prod", ".", "Batch", ".", "ReachedTimeThreshold", "(", "prod", ".", "batchTimeout", ")", "||", "prod", ".", "Batch", ".", "ReachedSizeThreshold", "(", "prod", ".", "batchFlushCount", ")", "{", "prod", ".", "flushBatch", "(", ")", "\n", "}", "\n", "}" ]
// flushBatchOnTimeOut is the used function pointer to flush the batch on timeout or reached max size
[ "flushBatchOnTimeOut", "is", "the", "used", "function", "pointer", "to", "flush", "the", "batch", "on", "timeout", "or", "reached", "max", "size" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/batchedproducer.go#L94-L98
142,562
trivago/gollum
core/batchedproducer.go
DefaultClose
func (prod *BatchedProducer) DefaultClose() { defer prod.WorkerDone() prod.Batch.Close(prod.onBatchFlush(), prod.GetShutdownTimeout()) }
go
func (prod *BatchedProducer) DefaultClose() { defer prod.WorkerDone() prod.Batch.Close(prod.onBatchFlush(), prod.GetShutdownTimeout()) }
[ "func", "(", "prod", "*", "BatchedProducer", ")", "DefaultClose", "(", ")", "{", "defer", "prod", ".", "WorkerDone", "(", ")", "\n", "prod", ".", "Batch", ".", "Close", "(", "prod", ".", "onBatchFlush", "(", ")", ",", "prod", ".", "GetShutdownTimeout", "(", ")", ")", "\n", "}" ]
// DefaultClose defines the default closing process
[ "DefaultClose", "defines", "the", "default", "closing", "process" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/batchedproducer.go#L109-L112
142,563
trivago/gollum
producer/null.go
Produce
func (prod *Null) Produce(threads *sync.WaitGroup) { prod.MessageControlLoop(func(*core.Message) {}) }
go
func (prod *Null) Produce(threads *sync.WaitGroup) { prod.MessageControlLoop(func(*core.Message) {}) }
[ "func", "(", "prod", "*", "Null", ")", "Produce", "(", "threads", "*", "sync", ".", "WaitGroup", ")", "{", "prod", ".", "MessageControlLoop", "(", "func", "(", "*", "core", ".", "Message", ")", "{", "}", ")", "\n", "}" ]
// Produce starts a control loop only
[ "Produce", "starts", "a", "control", "loop", "only" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/null.go#L41-L43
142,564
trivago/gollum
producer/file.go
Produce
func (prod *File) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) prod.TickerMessageControlLoop(prod.writeMessage, prod.BatchConfig.BatchTimeout, prod.writeBatchOnTimeOut) }
go
func (prod *File) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) prod.TickerMessageControlLoop(prod.writeMessage, prod.BatchConfig.BatchTimeout, prod.writeBatchOnTimeOut) }
[ "func", "(", "prod", "*", "File", ")", "Produce", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "prod", ".", "AddMainWorker", "(", "workers", ")", "\n", "prod", ".", "TickerMessageControlLoop", "(", "prod", ".", "writeMessage", ",", "prod", ".", "BatchConfig", ".", "BatchTimeout", ",", "prod", ".", "writeBatchOnTimeOut", ")", "\n", "}" ]
// Produce writes to a buffer that is dumped to a file.
[ "Produce", "writes", "to", "a", "buffer", "that", "is", "dumped", "to", "a", "file", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file.go#L117-L120
142,565
trivago/gollum
producer/kafkaMurmur2HashPartitioner.go
NewMurmur2HashPartitioner
func NewMurmur2HashPartitioner(topic string) kafka.Partitioner { p := new(Murmur2HashPartitioner) p.random = kafka.NewRandomPartitioner(topic) return p }
go
func NewMurmur2HashPartitioner(topic string) kafka.Partitioner { p := new(Murmur2HashPartitioner) p.random = kafka.NewRandomPartitioner(topic) return p }
[ "func", "NewMurmur2HashPartitioner", "(", "topic", "string", ")", "kafka", ".", "Partitioner", "{", "p", ":=", "new", "(", "Murmur2HashPartitioner", ")", "\n", "p", ".", "random", "=", "kafka", ".", "NewRandomPartitioner", "(", "topic", ")", "\n", "return", "p", "\n", "}" ]
// NewMurmur2HashPartitioner creates a new sarama partitioner based on the // murmur2 hash algorithm.
[ "NewMurmur2HashPartitioner", "creates", "a", "new", "sarama", "partitioner", "based", "on", "the", "murmur2", "hash", "algorithm", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/kafkaMurmur2HashPartitioner.go#L17-L21
142,566
trivago/gollum
producer/kafkaMurmur2HashPartitioner.go
Partition
func (p *Murmur2HashPartitioner) Partition(message *kafka.ProducerMessage, numPartitions int32) (int32, error) { if message.Key == nil { return p.random.Partition(message, numPartitions) } key, err := message.Key.Encode() if err != nil { return -1, err } // murmur2 implementation based on https://github.com/aappleby/smhasher/blob/master/src/MurmurHash2.cpp m := uint32(0x5bd1e995) r := uint32(24) seed := uint32(0x9747b28c) dataLen := uint32(len(key)) /* Initialize the hash to a 'random' value */ h := seed ^ dataLen /* Mix 4 bytes at a time into the hash */ data := key i := 0 for { if dataLen < 4 { break } k := *(*uint32)(unsafe.Pointer(&data[i*4])) k *= m k ^= k >> r k *= m h *= m h ^= k i++ dataLen -= 4 } /* Handle the last few bytes of the input array */ switch dataLen { case 3: h ^= uint32(data[i*4+2]) << 16 h ^= uint32(data[i*4+1]) << 8 h ^= uint32(data[i*4]) h *= m case 2: h ^= uint32(data[i*4+1]) << 8 h ^= uint32(data[i*4]) h *= m case 1: h ^= uint32(data[i*4]) h *= m default: } /* Do a few final mixes of the hash to ensure the last few * bytes are well-incorporated. */ h ^= h >> 13 h *= m h ^= h >> 15 // convert h to positive partition := (int32(h) & 0x7fffffff) % numPartitions return partition, nil }
go
func (p *Murmur2HashPartitioner) Partition(message *kafka.ProducerMessage, numPartitions int32) (int32, error) { if message.Key == nil { return p.random.Partition(message, numPartitions) } key, err := message.Key.Encode() if err != nil { return -1, err } // murmur2 implementation based on https://github.com/aappleby/smhasher/blob/master/src/MurmurHash2.cpp m := uint32(0x5bd1e995) r := uint32(24) seed := uint32(0x9747b28c) dataLen := uint32(len(key)) /* Initialize the hash to a 'random' value */ h := seed ^ dataLen /* Mix 4 bytes at a time into the hash */ data := key i := 0 for { if dataLen < 4 { break } k := *(*uint32)(unsafe.Pointer(&data[i*4])) k *= m k ^= k >> r k *= m h *= m h ^= k i++ dataLen -= 4 } /* Handle the last few bytes of the input array */ switch dataLen { case 3: h ^= uint32(data[i*4+2]) << 16 h ^= uint32(data[i*4+1]) << 8 h ^= uint32(data[i*4]) h *= m case 2: h ^= uint32(data[i*4+1]) << 8 h ^= uint32(data[i*4]) h *= m case 1: h ^= uint32(data[i*4]) h *= m default: } /* Do a few final mixes of the hash to ensure the last few * bytes are well-incorporated. */ h ^= h >> 13 h *= m h ^= h >> 15 // convert h to positive partition := (int32(h) & 0x7fffffff) % numPartitions return partition, nil }
[ "func", "(", "p", "*", "Murmur2HashPartitioner", ")", "Partition", "(", "message", "*", "kafka", ".", "ProducerMessage", ",", "numPartitions", "int32", ")", "(", "int32", ",", "error", ")", "{", "if", "message", ".", "Key", "==", "nil", "{", "return", "p", ".", "random", ".", "Partition", "(", "message", ",", "numPartitions", ")", "\n", "}", "\n", "key", ",", "err", ":=", "message", ".", "Key", ".", "Encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "// murmur2 implementation based on https://github.com/aappleby/smhasher/blob/master/src/MurmurHash2.cpp", "m", ":=", "uint32", "(", "0x5bd1e995", ")", "\n", "r", ":=", "uint32", "(", "24", ")", "\n", "seed", ":=", "uint32", "(", "0x9747b28c", ")", "\n", "dataLen", ":=", "uint32", "(", "len", "(", "key", ")", ")", "\n", "/* Initialize the hash to a 'random' value */", "h", ":=", "seed", "^", "dataLen", "\n\n", "/* Mix 4 bytes at a time into the hash */", "data", ":=", "key", "\n", "i", ":=", "0", "\n", "for", "{", "if", "dataLen", "<", "4", "{", "break", "\n", "}", "\n", "k", ":=", "*", "(", "*", "uint32", ")", "(", "unsafe", ".", "Pointer", "(", "&", "data", "[", "i", "*", "4", "]", ")", ")", "\n", "k", "*=", "m", "\n", "k", "^=", "k", ">>", "r", "\n", "k", "*=", "m", "\n\n", "h", "*=", "m", "\n", "h", "^=", "k", "\n", "i", "++", "\n", "dataLen", "-=", "4", "\n", "}", "\n\n", "/* Handle the last few bytes of the input array */", "switch", "dataLen", "{", "case", "3", ":", "h", "^=", "uint32", "(", "data", "[", "i", "*", "4", "+", "2", "]", ")", "<<", "16", "\n", "h", "^=", "uint32", "(", "data", "[", "i", "*", "4", "+", "1", "]", ")", "<<", "8", "\n", "h", "^=", "uint32", "(", "data", "[", "i", "*", "4", "]", ")", "\n", "h", "*=", "m", "\n", "case", "2", ":", "h", "^=", "uint32", "(", "data", "[", "i", "*", "4", "+", "1", "]", ")", "<<", "8", "\n", "h", "^=", "uint32", "(", "data", "[", "i", "*", "4", "]", ")", "\n", "h", "*=", "m", "\n", "case", "1", ":", "h", "^=", "uint32", "(", "data", "[", "i", "*", "4", "]", ")", "\n", "h", "*=", "m", "\n", "default", ":", "}", "\n\n", "/* Do a few final mixes of the hash to ensure the last few\n\t * bytes are well-incorporated. */", "h", "^=", "h", ">>", "13", "\n", "h", "*=", "m", "\n", "h", "^=", "h", ">>", "15", "\n\n", "// convert h to positive", "partition", ":=", "(", "int32", "(", "h", ")", "&", "0x7fffffff", ")", "%", "numPartitions", "\n\n", "return", "partition", ",", "nil", "\n\n", "}" ]
// Partition chooses a partition based on the murmur2 hash of the key. // If no key is given a random parition is chosen.
[ "Partition", "chooses", "a", "partition", "based", "on", "the", "murmur2", "hash", "of", "the", "key", ".", "If", "no", "key", "is", "given", "a", "random", "parition", "is", "chosen", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/kafkaMurmur2HashPartitioner.go#L25-L90
142,567
trivago/gollum
contrib/native/pcap/pcaphttp.go
Consume
func (cons *PcapHTTPConsumer) Consume(workers *sync.WaitGroup) { cons.initPcap() cons.AddMainWorker(workers) go cons.readPackets() cons.ControlLoop() }
go
func (cons *PcapHTTPConsumer) Consume(workers *sync.WaitGroup) { cons.initPcap() cons.AddMainWorker(workers) go cons.readPackets() cons.ControlLoop() }
[ "func", "(", "cons", "*", "PcapHTTPConsumer", ")", "Consume", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "cons", ".", "initPcap", "(", ")", "\n", "cons", ".", "AddMainWorker", "(", "workers", ")", "\n\n", "go", "cons", ".", "readPackets", "(", ")", "\n", "cons", ".", "ControlLoop", "(", ")", "\n", "}" ]
// Consume enables libpcap monitoring as configured.
[ "Consume", "enables", "libpcap", "monitoring", "as", "configured", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcaphttp.go#L237-L243
142,568
trivago/gollum
core/components/batchedWriterAssembly.go
Configure
func (c *BatchedWriterConfig) Configure(conf core.PluginConfigReader) { c.BatchFlushCount = tmath.MinI(c.BatchFlushCount, c.BatchMaxCount) }
go
func (c *BatchedWriterConfig) Configure(conf core.PluginConfigReader) { c.BatchFlushCount = tmath.MinI(c.BatchFlushCount, c.BatchMaxCount) }
[ "func", "(", "c", "*", "BatchedWriterConfig", ")", "Configure", "(", "conf", "core", ".", "PluginConfigReader", ")", "{", "c", ".", "BatchFlushCount", "=", "tmath", ".", "MinI", "(", "c", ".", "BatchFlushCount", ",", "c", ".", "BatchMaxCount", ")", "\n", "}" ]
// Configure interface implementation
[ "Configure", "interface", "implementation" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L57-L59
142,569
trivago/gollum
core/components/batchedWriterAssembly.go
NewBatchedWriterAssembly
func NewBatchedWriterAssembly(config BatchedWriterConfig, modulator core.Modulator, tryFallback func(*core.Message), logger logrus.FieldLogger) *BatchedWriterAssembly { return &BatchedWriterAssembly{ Batch: core.NewMessageBatch(config.BatchMaxCount), assembly: core.NewWriterAssembly(nil, tryFallback, modulator), config: config, logger: logger, } }
go
func NewBatchedWriterAssembly(config BatchedWriterConfig, modulator core.Modulator, tryFallback func(*core.Message), logger logrus.FieldLogger) *BatchedWriterAssembly { return &BatchedWriterAssembly{ Batch: core.NewMessageBatch(config.BatchMaxCount), assembly: core.NewWriterAssembly(nil, tryFallback, modulator), config: config, logger: logger, } }
[ "func", "NewBatchedWriterAssembly", "(", "config", "BatchedWriterConfig", ",", "modulator", "core", ".", "Modulator", ",", "tryFallback", "func", "(", "*", "core", ".", "Message", ")", ",", "logger", "logrus", ".", "FieldLogger", ")", "*", "BatchedWriterAssembly", "{", "return", "&", "BatchedWriterAssembly", "{", "Batch", ":", "core", ".", "NewMessageBatch", "(", "config", ".", "BatchMaxCount", ")", ",", "assembly", ":", "core", ".", "NewWriterAssembly", "(", "nil", ",", "tryFallback", ",", "modulator", ")", ",", "config", ":", "config", ",", "logger", ":", "logger", ",", "}", "\n", "}" ]
// NewBatchedWriterAssembly returns a new BatchedWriterAssembly instance
[ "NewBatchedWriterAssembly", "returns", "a", "new", "BatchedWriterAssembly", "instance" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L80-L87
142,570
trivago/gollum
core/components/batchedWriterAssembly.go
SetWriter
func (bwa *BatchedWriterAssembly) SetWriter(writer BatchedWriter) { bwa.writer = writer bwa.Created = time.Now() }
go
func (bwa *BatchedWriterAssembly) SetWriter(writer BatchedWriter) { bwa.writer = writer bwa.Created = time.Now() }
[ "func", "(", "bwa", "*", "BatchedWriterAssembly", ")", "SetWriter", "(", "writer", "BatchedWriter", ")", "{", "bwa", ".", "writer", "=", "writer", "\n", "bwa", ".", "Created", "=", "time", ".", "Now", "(", ")", "\n", "}" ]
// SetWriter set a BatchedWriter interface implementation
[ "SetWriter", "set", "a", "BatchedWriter", "interface", "implementation" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L95-L98
142,571
trivago/gollum
core/components/batchedWriterAssembly.go
GetWriterAndUnset
func (bwa *BatchedWriterAssembly) GetWriterAndUnset() BatchedWriter { writer := bwa.GetWriter() bwa.UnsetWriter() return writer }
go
func (bwa *BatchedWriterAssembly) GetWriterAndUnset() BatchedWriter { writer := bwa.GetWriter() bwa.UnsetWriter() return writer }
[ "func", "(", "bwa", "*", "BatchedWriterAssembly", ")", "GetWriterAndUnset", "(", ")", "BatchedWriter", "{", "writer", ":=", "bwa", ".", "GetWriter", "(", ")", "\n", "bwa", ".", "UnsetWriter", "(", ")", "\n", "return", "writer", "\n", "}" ]
// GetWriterAndUnset returns the current writer and unset it
[ "GetWriterAndUnset", "returns", "the", "current", "writer", "and", "unset", "it" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L106-L110
142,572
trivago/gollum
core/components/batchedWriterAssembly.go
Flush
func (bwa *BatchedWriterAssembly) Flush() { if bwa.writer != nil { bwa.assembly.SetWriter(bwa.writer) bwa.Batch.Flush(bwa.assembly.Write) } else { bwa.Batch.Flush(bwa.assembly.Flush) } }
go
func (bwa *BatchedWriterAssembly) Flush() { if bwa.writer != nil { bwa.assembly.SetWriter(bwa.writer) bwa.Batch.Flush(bwa.assembly.Write) } else { bwa.Batch.Flush(bwa.assembly.Flush) } }
[ "func", "(", "bwa", "*", "BatchedWriterAssembly", ")", "Flush", "(", ")", "{", "if", "bwa", ".", "writer", "!=", "nil", "{", "bwa", ".", "assembly", ".", "SetWriter", "(", "bwa", ".", "writer", ")", "\n", "bwa", ".", "Batch", ".", "Flush", "(", "bwa", ".", "assembly", ".", "Write", ")", "\n", "}", "else", "{", "bwa", ".", "Batch", ".", "Flush", "(", "bwa", ".", "assembly", ".", "Flush", ")", "\n", "}", "\n", "}" ]
// Flush flush the batch
[ "Flush", "flush", "the", "batch" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L118-L125
142,573
trivago/gollum
core/components/batchedWriterAssembly.go
Close
func (bwa *BatchedWriterAssembly) Close() { if bwa.writer != nil { bwa.assembly.SetWriter(bwa.writer) bwa.Batch.Close(bwa.assembly.Write, bwa.config.BatchFlushTimeout) } else { bwa.Batch.Close(bwa.assembly.Flush, bwa.config.BatchFlushTimeout) } bwa.writer.Close() }
go
func (bwa *BatchedWriterAssembly) Close() { if bwa.writer != nil { bwa.assembly.SetWriter(bwa.writer) bwa.Batch.Close(bwa.assembly.Write, bwa.config.BatchFlushTimeout) } else { bwa.Batch.Close(bwa.assembly.Flush, bwa.config.BatchFlushTimeout) } bwa.writer.Close() }
[ "func", "(", "bwa", "*", "BatchedWriterAssembly", ")", "Close", "(", ")", "{", "if", "bwa", ".", "writer", "!=", "nil", "{", "bwa", ".", "assembly", ".", "SetWriter", "(", "bwa", ".", "writer", ")", "\n", "bwa", ".", "Batch", ".", "Close", "(", "bwa", ".", "assembly", ".", "Write", ",", "bwa", ".", "config", ".", "BatchFlushTimeout", ")", "\n", "}", "else", "{", "bwa", ".", "Batch", ".", "Close", "(", "bwa", ".", "assembly", ".", "Flush", ",", "bwa", ".", "config", ".", "BatchFlushTimeout", ")", "\n", "}", "\n", "bwa", ".", "writer", ".", "Close", "(", ")", "\n", "}" ]
// Close closes batch and writer
[ "Close", "closes", "batch", "and", "writer" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L128-L136
142,574
trivago/gollum
core/components/batchedWriterAssembly.go
FlushOnTimeOut
func (bwa *BatchedWriterAssembly) FlushOnTimeOut() { if bwa.Batch.ReachedTimeThreshold(bwa.config.BatchTimeout) || bwa.Batch.ReachedSizeThreshold(bwa.config.BatchFlushCount) { bwa.Flush() } }
go
func (bwa *BatchedWriterAssembly) FlushOnTimeOut() { if bwa.Batch.ReachedTimeThreshold(bwa.config.BatchTimeout) || bwa.Batch.ReachedSizeThreshold(bwa.config.BatchFlushCount) { bwa.Flush() } }
[ "func", "(", "bwa", "*", "BatchedWriterAssembly", ")", "FlushOnTimeOut", "(", ")", "{", "if", "bwa", ".", "Batch", ".", "ReachedTimeThreshold", "(", "bwa", ".", "config", ".", "BatchTimeout", ")", "||", "bwa", ".", "Batch", ".", "ReachedSizeThreshold", "(", "bwa", ".", "config", ".", "BatchFlushCount", ")", "{", "bwa", ".", "Flush", "(", ")", "\n", "}", "\n", "}" ]
// FlushOnTimeOut checks if timeout or slush count reached and flush in this case
[ "FlushOnTimeOut", "checks", "if", "timeout", "or", "slush", "count", "reached", "and", "flush", "in", "this", "case" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L139-L143
142,575
trivago/gollum
core/components/batchedWriterAssembly.go
NeedsRotate
func (bwa *BatchedWriterAssembly) NeedsRotate(rotate RotateConfig, forceRotate bool) (bool, error) { // File does not exist? if !bwa.HasWriter() { bwa.logger.Debug("Rotate true: ", "no writer") return true, nil } // File can be accessed? if !bwa.GetWriter().IsAccessible() { bwa.logger.Debug("Rotate false: ", "no access") return false, errors.New("can' access file to rotate") } // File needs rotation? if !rotate.Enabled { bwa.logger.Debug("Rotate false: ", "not active") return false, nil } if forceRotate { bwa.logger.Debug("Rotate true: ", "forced") return true, nil } // File is too large? if bwa.GetWriter().Size() >= rotate.SizeByte { bwa.logger.Debug("Rotate true: ", "size > rotation size") return true, nil // ### return, too large ### } // File is too old? if time.Since(bwa.Created) >= rotate.Timeout { bwa.logger.Debug("Rotate true: ", "lifetime > timeout setting") return true, nil // ### return, too old ### } // RotateAt crossed? if rotate.AtHour > -1 && rotate.AtMinute > -1 { now := time.Now() rotateAt := time.Date(now.Year(), now.Month(), now.Day(), rotate.AtHour, rotate.AtMinute, 0, 0, now.Location()) if rotateAt.Before(bwa.Created) { return false, nil } if now.After(rotateAt) { bwa.logger.Debug("Rotate true: ", "rotateAt time reached") return true, nil // ### return, too old ### } } // nope, everything is ok return false, nil }
go
func (bwa *BatchedWriterAssembly) NeedsRotate(rotate RotateConfig, forceRotate bool) (bool, error) { // File does not exist? if !bwa.HasWriter() { bwa.logger.Debug("Rotate true: ", "no writer") return true, nil } // File can be accessed? if !bwa.GetWriter().IsAccessible() { bwa.logger.Debug("Rotate false: ", "no access") return false, errors.New("can' access file to rotate") } // File needs rotation? if !rotate.Enabled { bwa.logger.Debug("Rotate false: ", "not active") return false, nil } if forceRotate { bwa.logger.Debug("Rotate true: ", "forced") return true, nil } // File is too large? if bwa.GetWriter().Size() >= rotate.SizeByte { bwa.logger.Debug("Rotate true: ", "size > rotation size") return true, nil // ### return, too large ### } // File is too old? if time.Since(bwa.Created) >= rotate.Timeout { bwa.logger.Debug("Rotate true: ", "lifetime > timeout setting") return true, nil // ### return, too old ### } // RotateAt crossed? if rotate.AtHour > -1 && rotate.AtMinute > -1 { now := time.Now() rotateAt := time.Date(now.Year(), now.Month(), now.Day(), rotate.AtHour, rotate.AtMinute, 0, 0, now.Location()) if rotateAt.Before(bwa.Created) { return false, nil } if now.After(rotateAt) { bwa.logger.Debug("Rotate true: ", "rotateAt time reached") return true, nil // ### return, too old ### } } // nope, everything is ok return false, nil }
[ "func", "(", "bwa", "*", "BatchedWriterAssembly", ")", "NeedsRotate", "(", "rotate", "RotateConfig", ",", "forceRotate", "bool", ")", "(", "bool", ",", "error", ")", "{", "// File does not exist?", "if", "!", "bwa", ".", "HasWriter", "(", ")", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "\n", "}", "\n\n", "// File can be accessed?", "if", "!", "bwa", ".", "GetWriter", "(", ")", ".", "IsAccessible", "(", ")", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// File needs rotation?", "if", "!", "rotate", ".", "Enabled", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "false", ",", "nil", "\n", "}", "\n\n", "if", "forceRotate", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "\n", "}", "\n\n", "// File is too large?", "if", "bwa", ".", "GetWriter", "(", ")", ".", "Size", "(", ")", ">=", "rotate", ".", "SizeByte", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "// ### return, too large ###", "\n", "}", "\n\n", "// File is too old?", "if", "time", ".", "Since", "(", "bwa", ".", "Created", ")", ">=", "rotate", ".", "Timeout", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "// ### return, too old ###", "\n", "}", "\n\n", "// RotateAt crossed?", "if", "rotate", ".", "AtHour", ">", "-", "1", "&&", "rotate", ".", "AtMinute", ">", "-", "1", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "rotateAt", ":=", "time", ".", "Date", "(", "now", ".", "Year", "(", ")", ",", "now", ".", "Month", "(", ")", ",", "now", ".", "Day", "(", ")", ",", "rotate", ".", "AtHour", ",", "rotate", ".", "AtMinute", ",", "0", ",", "0", ",", "now", ".", "Location", "(", ")", ")", "\n\n", "if", "rotateAt", ".", "Before", "(", "bwa", ".", "Created", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "if", "now", ".", "After", "(", "rotateAt", ")", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "// ### return, too old ###", "\n", "}", "\n", "}", "\n\n", "// nope, everything is ok", "return", "false", ",", "nil", "\n", "}" ]
// NeedsRotate evaluate if the BatchedWriterAssembly need to rotate by the FileRotateConfig
[ "NeedsRotate", "evaluate", "if", "the", "BatchedWriterAssembly", "need", "to", "rotate", "by", "the", "FileRotateConfig" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L146-L199
142,576
trivago/gollum
producer/file/pruner.go
Configure
func (pruner *Pruner) Configure(conf core.PluginConfigReader) { if pruner.pruneSize > 0 && pruner.rotate.SizeByte > 0 { pruner.pruneSize -= pruner.rotate.SizeByte >> 20 if pruner.pruneSize <= 0 { pruner.pruneCount = 1 pruner.pruneSize = 0 } } }
go
func (pruner *Pruner) Configure(conf core.PluginConfigReader) { if pruner.pruneSize > 0 && pruner.rotate.SizeByte > 0 { pruner.pruneSize -= pruner.rotate.SizeByte >> 20 if pruner.pruneSize <= 0 { pruner.pruneCount = 1 pruner.pruneSize = 0 } } }
[ "func", "(", "pruner", "*", "Pruner", ")", "Configure", "(", "conf", "core", ".", "PluginConfigReader", ")", "{", "if", "pruner", ".", "pruneSize", ">", "0", "&&", "pruner", ".", "rotate", ".", "SizeByte", ">", "0", "{", "pruner", ".", "pruneSize", "-=", "pruner", ".", "rotate", ".", "SizeByte", ">>", "20", "\n", "if", "pruner", ".", "pruneSize", "<=", "0", "{", "pruner", ".", "pruneCount", "=", "1", "\n", "pruner", ".", "pruneSize", "=", "0", "\n", "}", "\n", "}", "\n", "}" ]
// Configure initializes this object with values from a plugin config.
[ "Configure", "initializes", "this", "object", "with", "values", "from", "a", "plugin", "config", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/pruner.go#L55-L63
142,577
trivago/gollum
producer/file/pruner.go
Prune
func (pruner *Pruner) Prune(baseFilePath string) { if pruner.pruneHours > 0 { pruner.pruneByHour(baseFilePath, pruner.pruneHours) } if pruner.pruneCount > 0 { pruner.pruneByCount(baseFilePath, pruner.pruneCount) } if pruner.pruneSize > 0 { pruner.pruneToSize(baseFilePath, pruner.pruneSize) } }
go
func (pruner *Pruner) Prune(baseFilePath string) { if pruner.pruneHours > 0 { pruner.pruneByHour(baseFilePath, pruner.pruneHours) } if pruner.pruneCount > 0 { pruner.pruneByCount(baseFilePath, pruner.pruneCount) } if pruner.pruneSize > 0 { pruner.pruneToSize(baseFilePath, pruner.pruneSize) } }
[ "func", "(", "pruner", "*", "Pruner", ")", "Prune", "(", "baseFilePath", "string", ")", "{", "if", "pruner", ".", "pruneHours", ">", "0", "{", "pruner", ".", "pruneByHour", "(", "baseFilePath", ",", "pruner", ".", "pruneHours", ")", "\n", "}", "\n", "if", "pruner", ".", "pruneCount", ">", "0", "{", "pruner", ".", "pruneByCount", "(", "baseFilePath", ",", "pruner", ".", "pruneCount", ")", "\n", "}", "\n", "if", "pruner", ".", "pruneSize", ">", "0", "{", "pruner", ".", "pruneToSize", "(", "baseFilePath", ",", "pruner", ".", "pruneSize", ")", "\n", "}", "\n", "}" ]
// Prune starts prune methods by hours, by count and by size
[ "Prune", "starts", "prune", "methods", "by", "hours", "by", "count", "and", "by", "size" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/pruner.go#L66-L76
142,578
trivago/gollum
contrib/native/kafka/librdkafka/message.go
UnmarshalBuffer
func UnmarshalBuffer(bufferPtr *C.buffer_t) []byte { length := int(bufferPtr.len) buffer := make([]byte, length) copy(buffer, (*[1 << 30]byte)(bufferPtr.data)[:length:length]) return buffer }
go
func UnmarshalBuffer(bufferPtr *C.buffer_t) []byte { length := int(bufferPtr.len) buffer := make([]byte, length) copy(buffer, (*[1 << 30]byte)(bufferPtr.data)[:length:length]) return buffer }
[ "func", "UnmarshalBuffer", "(", "bufferPtr", "*", "C", ".", "buffer_t", ")", "[", "]", "byte", "{", "length", ":=", "int", "(", "bufferPtr", ".", "len", ")", "\n", "buffer", ":=", "make", "(", "[", "]", "byte", ",", "length", ")", "\n", "copy", "(", "buffer", ",", "(", "*", "[", "1", "<<", "30", "]", "byte", ")", "(", "bufferPtr", ".", "data", ")", "[", ":", "length", ":", "length", "]", ")", "\n", "return", "buffer", "\n", "}" ]
// UnmarshalBuffer creates a byte slice copy from a buffer_t handle.
[ "UnmarshalBuffer", "creates", "a", "byte", "slice", "copy", "from", "a", "buffer_t", "handle", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/librdkafka/message.go#L59-L64
142,579
trivago/gollum
contrib/native/systemd/systemdconsumer.go
Consume
func (cons *SystemdConsumer) Consume(workers *sync.WaitGroup) { cons.AddMainWorker(workers) go cons.read() cons.ControlLoop() }
go
func (cons *SystemdConsumer) Consume(workers *sync.WaitGroup) { cons.AddMainWorker(workers) go cons.read() cons.ControlLoop() }
[ "func", "(", "cons", "*", "SystemdConsumer", ")", "Consume", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "cons", ".", "AddMainWorker", "(", "workers", ")", "\n", "go", "cons", ".", "read", "(", ")", "\n", "cons", ".", "ControlLoop", "(", ")", "\n", "}" ]
// Consume enables systemd forwarding as configured.
[ "Consume", "enables", "systemd", "forwarding", "as", "configured", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/systemd/systemdconsumer.go#L182-L186
142,580
trivago/gollum
contrib/native/kafka/librdkafka/client.go
Poll
func (cl *Client) Poll(timeout time.Duration) { if timeout < 0 { C.rd_kafka_poll(cl.handle, -1) } else { timeoutMs := C.int(timeout.Nanoseconds() / 1000000) C.rd_kafka_poll(cl.handle, timeoutMs) } }
go
func (cl *Client) Poll(timeout time.Duration) { if timeout < 0 { C.rd_kafka_poll(cl.handle, -1) } else { timeoutMs := C.int(timeout.Nanoseconds() / 1000000) C.rd_kafka_poll(cl.handle, timeoutMs) } }
[ "func", "(", "cl", "*", "Client", ")", "Poll", "(", "timeout", "time", ".", "Duration", ")", "{", "if", "timeout", "<", "0", "{", "C", ".", "rd_kafka_poll", "(", "cl", ".", "handle", ",", "-", "1", ")", "\n", "}", "else", "{", "timeoutMs", ":=", "C", ".", "int", "(", "timeout", ".", "Nanoseconds", "(", ")", "/", "1000000", ")", "\n", "C", ".", "rd_kafka_poll", "(", "cl", ".", "handle", ",", "timeoutMs", ")", "\n", "}", "\n", "}" ]
// Poll polls for new data to be sent to the async handler functions
[ "Poll", "polls", "for", "new", "data", "to", "be", "sent", "to", "the", "async", "handler", "functions" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/librdkafka/client.go#L63-L70
142,581
trivago/gollum
contrib/deprecated/producer/s3.go
Produce
func (prod *S3) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) sess, err := session.NewSessionWithOptions(session.Options{ Config: *prod.config, SharedConfigState: session.SharedConfigEnable, }) if err != nil { prod.Logger.WithError(err).Error("Failed to create session") } if prod.assumeRole != "" { creds := stscreds.NewCredentials(sess, prod.assumeRole) prod.client = s3.New(sess, &aws.Config{Credentials: creds}) } else { prod.client = s3.New(sess) } prod.TickerMessageControlLoop(prod.bufferMessage, prod.flushFrequency, prod.sendBatchOnTimeOut) }
go
func (prod *S3) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) sess, err := session.NewSessionWithOptions(session.Options{ Config: *prod.config, SharedConfigState: session.SharedConfigEnable, }) if err != nil { prod.Logger.WithError(err).Error("Failed to create session") } if prod.assumeRole != "" { creds := stscreds.NewCredentials(sess, prod.assumeRole) prod.client = s3.New(sess, &aws.Config{Credentials: creds}) } else { prod.client = s3.New(sess) } prod.TickerMessageControlLoop(prod.bufferMessage, prod.flushFrequency, prod.sendBatchOnTimeOut) }
[ "func", "(", "prod", "*", "S3", ")", "Produce", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "prod", ".", "AddMainWorker", "(", "workers", ")", "\n", "sess", ",", "err", ":=", "session", ".", "NewSessionWithOptions", "(", "session", ".", "Options", "{", "Config", ":", "*", "prod", ".", "config", ",", "SharedConfigState", ":", "session", ".", "SharedConfigEnable", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "prod", ".", "Logger", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "prod", ".", "assumeRole", "!=", "\"", "\"", "{", "creds", ":=", "stscreds", ".", "NewCredentials", "(", "sess", ",", "prod", ".", "assumeRole", ")", "\n", "prod", ".", "client", "=", "s3", ".", "New", "(", "sess", ",", "&", "aws", ".", "Config", "{", "Credentials", ":", "creds", "}", ")", "\n", "}", "else", "{", "prod", ".", "client", "=", "s3", ".", "New", "(", "sess", ")", "\n", "}", "\n\n", "prod", ".", "TickerMessageControlLoop", "(", "prod", ".", "bufferMessage", ",", "prod", ".", "flushFrequency", ",", "prod", ".", "sendBatchOnTimeOut", ")", "\n", "}" ]
// Produce writes to a buffer that is sent to amazon s3.
[ "Produce", "writes", "to", "a", "buffer", "that", "is", "sent", "to", "amazon", "s3", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/deprecated/producer/s3.go#L587-L605
142,582
trivago/gollum
core/message.go
NewMessage
func NewMessage(source MessageSource, data []byte, metadata Metadata, streamID MessageStreamID) *Message { msg := &Message{ source: source, streamID: streamID, origStreamID: streamID, timestamp: time.Now().UnixNano(), } msg.data.payload = getPayloadCopy(data) if metadata != nil && len(metadata) > 0 { msg.data.metadata = metadata } return msg }
go
func NewMessage(source MessageSource, data []byte, metadata Metadata, streamID MessageStreamID) *Message { msg := &Message{ source: source, streamID: streamID, origStreamID: streamID, timestamp: time.Now().UnixNano(), } msg.data.payload = getPayloadCopy(data) if metadata != nil && len(metadata) > 0 { msg.data.metadata = metadata } return msg }
[ "func", "NewMessage", "(", "source", "MessageSource", ",", "data", "[", "]", "byte", ",", "metadata", "Metadata", ",", "streamID", "MessageStreamID", ")", "*", "Message", "{", "msg", ":=", "&", "Message", "{", "source", ":", "source", ",", "streamID", ":", "streamID", ",", "origStreamID", ":", "streamID", ",", "timestamp", ":", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ",", "}", "\n\n", "msg", ".", "data", ".", "payload", "=", "getPayloadCopy", "(", "data", ")", "\n", "if", "metadata", "!=", "nil", "&&", "len", "(", "metadata", ")", ">", "0", "{", "msg", ".", "data", ".", "metadata", "=", "metadata", "\n", "}", "\n\n", "return", "msg", "\n", "}" ]
// NewMessage creates a new message from a given data stream by copying data.
[ "NewMessage", "creates", "a", "new", "message", "from", "a", "given", "data", "stream", "by", "copying", "data", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L43-L57
142,583
trivago/gollum
core/message.go
getPayloadCopy
func getPayloadCopy(data []byte) (buffer []byte) { buffer = make([]byte, len(data)) copy(buffer, data) return }
go
func getPayloadCopy(data []byte) (buffer []byte) { buffer = make([]byte, len(data)) copy(buffer, data) return }
[ "func", "getPayloadCopy", "(", "data", "[", "]", "byte", ")", "(", "buffer", "[", "]", "byte", ")", "{", "buffer", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "data", ")", ")", "\n", "copy", "(", "buffer", ",", "data", ")", "\n", "return", "\n", "}" ]
// getPayloadCopy return a copy of the data byte array
[ "getPayloadCopy", "return", "a", "copy", "of", "the", "data", "byte", "array" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L60-L64
142,584
trivago/gollum
core/message.go
SetStreamID
func (msg *Message) SetStreamID(streamID MessageStreamID) { msg.prevStreamID = msg.streamID msg.streamID = streamID }
go
func (msg *Message) SetStreamID(streamID MessageStreamID) { msg.prevStreamID = msg.streamID msg.streamID = streamID }
[ "func", "(", "msg", "*", "Message", ")", "SetStreamID", "(", "streamID", "MessageStreamID", ")", "{", "msg", ".", "prevStreamID", "=", "msg", ".", "streamID", "\n", "msg", ".", "streamID", "=", "streamID", "\n", "}" ]
// SetStreamID sets a new stream and stores the current one in the previous // stream field. This method does not affect the original stream ID.
[ "SetStreamID", "sets", "a", "new", "stream", "and", "stores", "the", "current", "one", "in", "the", "previous", "stream", "field", ".", "This", "method", "does", "not", "affect", "the", "original", "stream", "ID", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L103-L106
142,585
trivago/gollum
core/message.go
GetMetadata
func (msg *Message) GetMetadata() Metadata { if msg.data.metadata == nil { msg.data.metadata = make(Metadata) } return msg.data.metadata }
go
func (msg *Message) GetMetadata() Metadata { if msg.data.metadata == nil { msg.data.metadata = make(Metadata) } return msg.data.metadata }
[ "func", "(", "msg", "*", "Message", ")", "GetMetadata", "(", ")", "Metadata", "{", "if", "msg", ".", "data", ".", "metadata", "==", "nil", "{", "msg", ".", "data", ".", "metadata", "=", "make", "(", "Metadata", ")", "\n", "}", "\n", "return", "msg", ".", "data", ".", "metadata", "\n", "}" ]
// GetMetadata returns the current Metadata. If no metadata is present, the // metadata map will be created by this call.
[ "GetMetadata", "returns", "the", "current", "Metadata", ".", "If", "no", "metadata", "is", "present", "the", "metadata", "map", "will", "be", "created", "by", "this", "call", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L133-L138
142,586
trivago/gollum
core/message.go
StorePayload
func (msg *Message) StorePayload(data []byte) { if len(data) <= cap(msg.data.payload) { msg.data.payload = msg.data.payload[:len(data)] copy(msg.data.payload, data) } else { msg.data.payload = data } }
go
func (msg *Message) StorePayload(data []byte) { if len(data) <= cap(msg.data.payload) { msg.data.payload = msg.data.payload[:len(data)] copy(msg.data.payload, data) } else { msg.data.payload = data } }
[ "func", "(", "msg", "*", "Message", ")", "StorePayload", "(", "data", "[", "]", "byte", ")", "{", "if", "len", "(", "data", ")", "<=", "cap", "(", "msg", ".", "data", ".", "payload", ")", "{", "msg", ".", "data", ".", "payload", "=", "msg", ".", "data", ".", "payload", "[", ":", "len", "(", "data", ")", "]", "\n", "copy", "(", "msg", ".", "data", ".", "payload", ",", "data", ")", "\n", "}", "else", "{", "msg", ".", "data", ".", "payload", "=", "data", "\n", "}", "\n", "}" ]
// StorePayload copies data into the hold data buffer. If the buffer can hold // data it is resized, otherwise a new buffer will be allocated.
[ "StorePayload", "copies", "data", "into", "the", "hold", "data", "buffer", ".", "If", "the", "buffer", "can", "hold", "data", "it", "is", "resized", "otherwise", "a", "new", "buffer", "will", "be", "allocated", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L148-L155
142,587
trivago/gollum
core/message.go
Clone
func (msg *Message) Clone() *Message { clone := *msg clone.data.payload = make([]byte, len(msg.data.payload)) copy(clone.data.payload, msg.data.payload) return &clone }
go
func (msg *Message) Clone() *Message { clone := *msg clone.data.payload = make([]byte, len(msg.data.payload)) copy(clone.data.payload, msg.data.payload) return &clone }
[ "func", "(", "msg", "*", "Message", ")", "Clone", "(", ")", "*", "Message", "{", "clone", ":=", "*", "msg", "\n\n", "clone", ".", "data", ".", "payload", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "msg", ".", "data", ".", "payload", ")", ")", "\n", "copy", "(", "clone", ".", "data", ".", "payload", ",", "msg", ".", "data", ".", "payload", ")", "\n\n", "return", "&", "clone", "\n", "}" ]
// Clone returns a copy of this message, i.e. the payload is duplicated. // The created timestamp is copied, too.
[ "Clone", "returns", "a", "copy", "of", "this", "message", "i", ".", "e", ".", "the", "payload", "is", "duplicated", ".", "The", "created", "timestamp", "is", "copied", "too", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L159-L166
142,588
trivago/gollum
core/message.go
CloneOriginal
func (msg *Message) CloneOriginal() *Message { if msg.orig == nil { msg.FreezeOriginal() } clone := *msg clone.data.payload = make([]byte, len(msg.orig.payload)) copy(clone.data.payload, msg.orig.payload) if msg.orig.metadata != nil { clone.data.metadata = msg.orig.metadata.Clone() } else { clone.data.metadata = nil } clone.SetStreamID(msg.origStreamID) return &clone }
go
func (msg *Message) CloneOriginal() *Message { if msg.orig == nil { msg.FreezeOriginal() } clone := *msg clone.data.payload = make([]byte, len(msg.orig.payload)) copy(clone.data.payload, msg.orig.payload) if msg.orig.metadata != nil { clone.data.metadata = msg.orig.metadata.Clone() } else { clone.data.metadata = nil } clone.SetStreamID(msg.origStreamID) return &clone }
[ "func", "(", "msg", "*", "Message", ")", "CloneOriginal", "(", ")", "*", "Message", "{", "if", "msg", ".", "orig", "==", "nil", "{", "msg", ".", "FreezeOriginal", "(", ")", "\n", "}", "\n\n", "clone", ":=", "*", "msg", "\n", "clone", ".", "data", ".", "payload", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "msg", ".", "orig", ".", "payload", ")", ")", "\n", "copy", "(", "clone", ".", "data", ".", "payload", ",", "msg", ".", "orig", ".", "payload", ")", "\n\n", "if", "msg", ".", "orig", ".", "metadata", "!=", "nil", "{", "clone", ".", "data", ".", "metadata", "=", "msg", ".", "orig", ".", "metadata", ".", "Clone", "(", ")", "\n", "}", "else", "{", "clone", ".", "data", ".", "metadata", "=", "nil", "\n", "}", "\n\n", "clone", ".", "SetStreamID", "(", "msg", ".", "origStreamID", ")", "\n", "return", "&", "clone", "\n", "}" ]
// CloneOriginal returns a copy of this message with the original payload and // stream. If FreezeOriginal has not been called before it will be at this point // so that all subsequential calls will use the same original.
[ "CloneOriginal", "returns", "a", "copy", "of", "this", "message", "with", "the", "original", "payload", "and", "stream", ".", "If", "FreezeOriginal", "has", "not", "been", "called", "before", "it", "will", "be", "at", "this", "point", "so", "that", "all", "subsequential", "calls", "will", "use", "the", "same", "original", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L171-L188
142,589
trivago/gollum
core/message.go
FreezeOriginal
func (msg *Message) FreezeOriginal() { // Freeze may be called only once if msg.orig != nil { return } var metadata Metadata if msg.data.metadata != nil { metadata = msg.data.metadata.Clone() } msg.orig = &MessageData{ payload: getPayloadCopy(msg.data.payload), metadata: metadata, } }
go
func (msg *Message) FreezeOriginal() { // Freeze may be called only once if msg.orig != nil { return } var metadata Metadata if msg.data.metadata != nil { metadata = msg.data.metadata.Clone() } msg.orig = &MessageData{ payload: getPayloadCopy(msg.data.payload), metadata: metadata, } }
[ "func", "(", "msg", "*", "Message", ")", "FreezeOriginal", "(", ")", "{", "// Freeze may be called only once", "if", "msg", ".", "orig", "!=", "nil", "{", "return", "\n", "}", "\n\n", "var", "metadata", "Metadata", "\n", "if", "msg", ".", "data", ".", "metadata", "!=", "nil", "{", "metadata", "=", "msg", ".", "data", ".", "metadata", ".", "Clone", "(", ")", "\n", "}", "\n\n", "msg", ".", "orig", "=", "&", "MessageData", "{", "payload", ":", "getPayloadCopy", "(", "msg", ".", "data", ".", "payload", ")", ",", "metadata", ":", "metadata", ",", "}", "\n", "}" ]
// FreezeOriginal will take the current state of the message and store it as // the "original" message. This function can only be called once for each // message. Please note that this function only affects payload and metadata and // can only be called once. Additional calls will have no effect. // The original stream ID can be changed at any time by using SetOrigStreamID.
[ "FreezeOriginal", "will", "take", "the", "current", "state", "of", "the", "message", "and", "store", "it", "as", "the", "original", "message", ".", "This", "function", "can", "only", "be", "called", "once", "for", "each", "message", ".", "Please", "note", "that", "this", "function", "only", "affects", "payload", "and", "metadata", "and", "can", "only", "be", "called", "once", ".", "Additional", "calls", "will", "have", "no", "effect", ".", "The", "original", "stream", "ID", "can", "be", "changed", "at", "any", "time", "by", "using", "SetOrigStreamID", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L195-L210
142,590
trivago/gollum
core/message.go
DeserializeMessage
func DeserializeMessage(data []byte) (*Message, error) { serializable := new(SerializedMessage) if err := proto.Unmarshal(data, serializable); err != nil { return nil, err } msg := &Message{ streamID: MessageStreamID(serializable.GetStreamID()), prevStreamID: MessageStreamID(serializable.GetPrevStreamID()), origStreamID: MessageStreamID(serializable.GetOrigStreamID()), timestamp: serializable.GetTimestamp(), } if msgData := serializable.GetData(); msgData != nil { msg.data.payload = msgData.GetData() msg.data.metadata = msgData.GetMetadata() } if msgOrigData := serializable.GetOriginal(); msgOrigData != nil { msg.orig = new(MessageData) msg.orig.payload = msgOrigData.GetData() msg.orig.metadata = msgOrigData.GetMetadata() } return msg, nil }
go
func DeserializeMessage(data []byte) (*Message, error) { serializable := new(SerializedMessage) if err := proto.Unmarshal(data, serializable); err != nil { return nil, err } msg := &Message{ streamID: MessageStreamID(serializable.GetStreamID()), prevStreamID: MessageStreamID(serializable.GetPrevStreamID()), origStreamID: MessageStreamID(serializable.GetOrigStreamID()), timestamp: serializable.GetTimestamp(), } if msgData := serializable.GetData(); msgData != nil { msg.data.payload = msgData.GetData() msg.data.metadata = msgData.GetMetadata() } if msgOrigData := serializable.GetOriginal(); msgOrigData != nil { msg.orig = new(MessageData) msg.orig.payload = msgOrigData.GetData() msg.orig.metadata = msgOrigData.GetMetadata() } return msg, nil }
[ "func", "DeserializeMessage", "(", "data", "[", "]", "byte", ")", "(", "*", "Message", ",", "error", ")", "{", "serializable", ":=", "new", "(", "SerializedMessage", ")", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "data", ",", "serializable", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "msg", ":=", "&", "Message", "{", "streamID", ":", "MessageStreamID", "(", "serializable", ".", "GetStreamID", "(", ")", ")", ",", "prevStreamID", ":", "MessageStreamID", "(", "serializable", ".", "GetPrevStreamID", "(", ")", ")", ",", "origStreamID", ":", "MessageStreamID", "(", "serializable", ".", "GetOrigStreamID", "(", ")", ")", ",", "timestamp", ":", "serializable", ".", "GetTimestamp", "(", ")", ",", "}", "\n\n", "if", "msgData", ":=", "serializable", ".", "GetData", "(", ")", ";", "msgData", "!=", "nil", "{", "msg", ".", "data", ".", "payload", "=", "msgData", ".", "GetData", "(", ")", "\n", "msg", ".", "data", ".", "metadata", "=", "msgData", ".", "GetMetadata", "(", ")", "\n", "}", "\n\n", "if", "msgOrigData", ":=", "serializable", ".", "GetOriginal", "(", ")", ";", "msgOrigData", "!=", "nil", "{", "msg", ".", "orig", "=", "new", "(", "MessageData", ")", "\n", "msg", ".", "orig", ".", "payload", "=", "msgOrigData", ".", "GetData", "(", ")", "\n", "msg", ".", "orig", ".", "metadata", "=", "msgOrigData", ".", "GetMetadata", "(", ")", "\n", "}", "\n\n", "return", "msg", ",", "nil", "\n", "}" ]
// DeserializeMessage generates a message from a byte array produced by // Message.Serialize. Please note that the payload is restored but the original // data is not. As of this FreezeOriginal can be called again after this call.
[ "DeserializeMessage", "generates", "a", "message", "from", "a", "byte", "array", "produced", "by", "Message", ".", "Serialize", ".", "Please", "note", "that", "the", "payload", "is", "restored", "but", "the", "original", "data", "is", "not", ".", "As", "of", "this", "FreezeOriginal", "can", "be", "called", "again", "after", "this", "call", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L241-L266
142,591
trivago/gollum
producer/spooling.go
TryFallback
func (prod *Spooling) TryFallback(msg *core.Message) { if prod.revertOnDrop { msg.SetStreamID(msg.GetPrevStreamID()) } prod.BufferedProducer.TryFallback(msg) }
go
func (prod *Spooling) TryFallback(msg *core.Message) { if prod.revertOnDrop { msg.SetStreamID(msg.GetPrevStreamID()) } prod.BufferedProducer.TryFallback(msg) }
[ "func", "(", "prod", "*", "Spooling", ")", "TryFallback", "(", "msg", "*", "core", ".", "Message", ")", "{", "if", "prod", ".", "revertOnDrop", "{", "msg", ".", "SetStreamID", "(", "msg", ".", "GetPrevStreamID", "(", ")", ")", "\n", "}", "\n", "prod", ".", "BufferedProducer", ".", "TryFallback", "(", "msg", ")", "\n", "}" ]
// TryFallback reverts the message stream before dropping
[ "TryFallback", "reverts", "the", "message", "stream", "before", "dropping" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/spooling.go#L142-L147
142,592
trivago/gollum
producer/spooling.go
openExistingFiles
func (prod *Spooling) openExistingFiles() { prod.Logger.Debug("Looking for spool files to read") files, _ := ioutil.ReadDir(prod.path) for _, file := range files { if file.IsDir() { streamName := filepath.Base(file.Name()) streamID := core.StreamRegistry.GetStreamID(streamName) // Only create a new spooler if the stream is registered by this instance prod.outfileGuard.Lock() if _, exists := prod.outfile[streamID]; !exists && core.StreamRegistry.IsStreamRegistered(streamID) { prod.Logger.Infof("Found existing spooling folders for %s", streamName) prod.outfile[streamID] = newSpoolFile(prod, streamName, nil) } prod.outfileGuard.Unlock() } } // Keep looking for new streams if prod.IsActive() { prod.spoolCheck = time.AfterFunc(prod.respoolDuration, prod.openExistingFiles) } }
go
func (prod *Spooling) openExistingFiles() { prod.Logger.Debug("Looking for spool files to read") files, _ := ioutil.ReadDir(prod.path) for _, file := range files { if file.IsDir() { streamName := filepath.Base(file.Name()) streamID := core.StreamRegistry.GetStreamID(streamName) // Only create a new spooler if the stream is registered by this instance prod.outfileGuard.Lock() if _, exists := prod.outfile[streamID]; !exists && core.StreamRegistry.IsStreamRegistered(streamID) { prod.Logger.Infof("Found existing spooling folders for %s", streamName) prod.outfile[streamID] = newSpoolFile(prod, streamName, nil) } prod.outfileGuard.Unlock() } } // Keep looking for new streams if prod.IsActive() { prod.spoolCheck = time.AfterFunc(prod.respoolDuration, prod.openExistingFiles) } }
[ "func", "(", "prod", "*", "Spooling", ")", "openExistingFiles", "(", ")", "{", "prod", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "files", ",", "_", ":=", "ioutil", ".", "ReadDir", "(", "prod", ".", "path", ")", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "if", "file", ".", "IsDir", "(", ")", "{", "streamName", ":=", "filepath", ".", "Base", "(", "file", ".", "Name", "(", ")", ")", "\n", "streamID", ":=", "core", ".", "StreamRegistry", ".", "GetStreamID", "(", "streamName", ")", "\n\n", "// Only create a new spooler if the stream is registered by this instance", "prod", ".", "outfileGuard", ".", "Lock", "(", ")", "\n", "if", "_", ",", "exists", ":=", "prod", ".", "outfile", "[", "streamID", "]", ";", "!", "exists", "&&", "core", ".", "StreamRegistry", ".", "IsStreamRegistered", "(", "streamID", ")", "{", "prod", ".", "Logger", ".", "Infof", "(", "\"", "\"", ",", "streamName", ")", "\n", "prod", ".", "outfile", "[", "streamID", "]", "=", "newSpoolFile", "(", "prod", ",", "streamName", ",", "nil", ")", "\n", "}", "\n", "prod", ".", "outfileGuard", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n\n", "// Keep looking for new streams", "if", "prod", ".", "IsActive", "(", ")", "{", "prod", ".", "spoolCheck", "=", "time", ".", "AfterFunc", "(", "prod", ".", "respoolDuration", ",", "prod", ".", "openExistingFiles", ")", "\n", "}", "\n", "}" ]
// As we might share spooling folders with different instances we only read // streams that we actually care about.
[ "As", "we", "might", "share", "spooling", "folders", "with", "different", "instances", "we", "only", "read", "streams", "that", "we", "actually", "care", "about", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/spooling.go#L288-L310
142,593
trivago/gollum
core/bufferedproducer.go
DefaultDrain
func (prod *BufferedProducer) DefaultDrain() { if prod.onMessage != nil { prod.DrainMessageChannel(prod.onMessage, prod.shutdownTimeout) } }
go
func (prod *BufferedProducer) DefaultDrain() { if prod.onMessage != nil { prod.DrainMessageChannel(prod.onMessage, prod.shutdownTimeout) } }
[ "func", "(", "prod", "*", "BufferedProducer", ")", "DefaultDrain", "(", ")", "{", "if", "prod", ".", "onMessage", "!=", "nil", "{", "prod", ".", "DrainMessageChannel", "(", "prod", ".", "onMessage", ",", "prod", ".", "shutdownTimeout", ")", "\n", "}", "\n", "}" ]
// DefaultDrain is the function registered to onPrepareStop by default. // It calls DrainMessageChannel with the message handling function passed to // Any of the control functions. If no such call happens, this function does // nothing.
[ "DefaultDrain", "is", "the", "function", "registered", "to", "onPrepareStop", "by", "default", ".", "It", "calls", "DrainMessageChannel", "with", "the", "message", "handling", "function", "passed", "to", "Any", "of", "the", "control", "functions", ".", "If", "no", "such", "call", "happens", "this", "function", "does", "nothing", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/bufferedproducer.go#L101-L105
142,594
trivago/gollum
core/bufferedproducer.go
DrainMessageChannel
func (prod *BufferedProducer) DrainMessageChannel(handleMessage func(*Message), timeout time.Duration) bool { for { if msg, ok := prod.messages.PopWithTimeout(timeout); ok { if !tgo.ReturnAfter(prod.shutdownTimeout, func() { handleMessage(msg) }) { return false // ### return, done ### } } else { return prod.messages.IsEmpty() // ### return, done ### } } }
go
func (prod *BufferedProducer) DrainMessageChannel(handleMessage func(*Message), timeout time.Duration) bool { for { if msg, ok := prod.messages.PopWithTimeout(timeout); ok { if !tgo.ReturnAfter(prod.shutdownTimeout, func() { handleMessage(msg) }) { return false // ### return, done ### } } else { return prod.messages.IsEmpty() // ### return, done ### } } }
[ "func", "(", "prod", "*", "BufferedProducer", ")", "DrainMessageChannel", "(", "handleMessage", "func", "(", "*", "Message", ")", ",", "timeout", "time", ".", "Duration", ")", "bool", "{", "for", "{", "if", "msg", ",", "ok", ":=", "prod", ".", "messages", ".", "PopWithTimeout", "(", "timeout", ")", ";", "ok", "{", "if", "!", "tgo", ".", "ReturnAfter", "(", "prod", ".", "shutdownTimeout", ",", "func", "(", ")", "{", "handleMessage", "(", "msg", ")", "}", ")", "{", "return", "false", "// ### return, done ###", "\n", "}", "\n", "}", "else", "{", "return", "prod", ".", "messages", ".", "IsEmpty", "(", ")", "// ### return, done ###", "\n", "}", "\n", "}", "\n", "}" ]
// DrainMessageChannel empties the message channel. This functions returns // after the queue being empty for a given amount of time or when the queue // has been closed and no more messages are available. The return value // indicates wether the channel is empty or not.
[ "DrainMessageChannel", "empties", "the", "message", "channel", ".", "This", "functions", "returns", "after", "the", "queue", "being", "empty", "for", "a", "given", "amount", "of", "time", "or", "when", "the", "queue", "has", "been", "closed", "and", "no", "more", "messages", "are", "available", ".", "The", "return", "value", "indicates", "wether", "the", "channel", "is", "empty", "or", "not", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/bufferedproducer.go#L111-L121
142,595
trivago/gollum
core/bufferedproducer.go
DefaultClose
func (prod *BufferedProducer) DefaultClose() { if prod.onMessage != nil { prod.CloseMessageChannel(prod.onMessage) } }
go
func (prod *BufferedProducer) DefaultClose() { if prod.onMessage != nil { prod.CloseMessageChannel(prod.onMessage) } }
[ "func", "(", "prod", "*", "BufferedProducer", ")", "DefaultClose", "(", ")", "{", "if", "prod", ".", "onMessage", "!=", "nil", "{", "prod", ".", "CloseMessageChannel", "(", "prod", ".", "onMessage", ")", "\n", "}", "\n", "}" ]
// DefaultClose is the function registered to onStop by default. // It calls CloseMessageChannel with the message handling function passed to // Any of the control functions. If no such call happens, this function does // nothing.
[ "DefaultClose", "is", "the", "function", "registered", "to", "onStop", "by", "default", ".", "It", "calls", "CloseMessageChannel", "with", "the", "message", "handling", "function", "passed", "to", "Any", "of", "the", "control", "functions", ".", "If", "no", "such", "call", "happens", "this", "function", "does", "nothing", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/bufferedproducer.go#L127-L131
142,596
trivago/gollum
core/bufferedproducer.go
CloseMessageChannel
func (prod *BufferedProducer) CloseMessageChannel(handleMessage func(*Message)) (empty bool) { prod.DrainMessageChannel(handleMessage, prod.shutdownTimeout) prod.messages.Close() defer func() { if !prod.messages.IsEmpty() { prod.Logger.Errorf("%d messages left after closing.", prod.messages.GetNumQueued()) } }() for { if msg, ok := prod.messages.Pop(); ok { if !tgo.ReturnAfter(prod.shutdownTimeout, func() { handleMessage(msg) }) { return false // ### return, failed to handle message ### } } else { return true // ### return, done ### } } }
go
func (prod *BufferedProducer) CloseMessageChannel(handleMessage func(*Message)) (empty bool) { prod.DrainMessageChannel(handleMessage, prod.shutdownTimeout) prod.messages.Close() defer func() { if !prod.messages.IsEmpty() { prod.Logger.Errorf("%d messages left after closing.", prod.messages.GetNumQueued()) } }() for { if msg, ok := prod.messages.Pop(); ok { if !tgo.ReturnAfter(prod.shutdownTimeout, func() { handleMessage(msg) }) { return false // ### return, failed to handle message ### } } else { return true // ### return, done ### } } }
[ "func", "(", "prod", "*", "BufferedProducer", ")", "CloseMessageChannel", "(", "handleMessage", "func", "(", "*", "Message", ")", ")", "(", "empty", "bool", ")", "{", "prod", ".", "DrainMessageChannel", "(", "handleMessage", ",", "prod", ".", "shutdownTimeout", ")", "\n", "prod", ".", "messages", ".", "Close", "(", ")", "\n\n", "defer", "func", "(", ")", "{", "if", "!", "prod", ".", "messages", ".", "IsEmpty", "(", ")", "{", "prod", ".", "Logger", ".", "Errorf", "(", "\"", "\"", ",", "prod", ".", "messages", ".", "GetNumQueued", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "for", "{", "if", "msg", ",", "ok", ":=", "prod", ".", "messages", ".", "Pop", "(", ")", ";", "ok", "{", "if", "!", "tgo", ".", "ReturnAfter", "(", "prod", ".", "shutdownTimeout", ",", "func", "(", ")", "{", "handleMessage", "(", "msg", ")", "}", ")", "{", "return", "false", "// ### return, failed to handle message ###", "\n", "}", "\n", "}", "else", "{", "return", "true", "// ### return, done ###", "\n", "}", "\n", "}", "\n", "}" ]
// CloseMessageChannel first calls DrainMessageChannel with shutdown timeout, // closes the channel afterwards and calls DrainMessageChannel again to make // sure all messages are actually gone. The return value indicates wether // the channel is empty or not.
[ "CloseMessageChannel", "first", "calls", "DrainMessageChannel", "with", "shutdown", "timeout", "closes", "the", "channel", "afterwards", "and", "calls", "DrainMessageChannel", "again", "to", "make", "sure", "all", "messages", "are", "actually", "gone", ".", "The", "return", "value", "indicates", "wether", "the", "channel", "is", "empty", "or", "not", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/bufferedproducer.go#L137-L156
142,597
trivago/gollum
core/logconsumer.go
Consume
func (cons *LogConsumer) Consume(threads *sync.WaitGroup) { // Wait for control statements for { select { case msg := <-cons.queue: cons.logRouter.Enqueue(msg) case command := <-cons.control: if command == PluginControlStopConsumer { cons.queue.Close() for msg := range cons.queue { cons.logRouter.Enqueue(msg) } cons.stopped = true return // ### return ### } } } }
go
func (cons *LogConsumer) Consume(threads *sync.WaitGroup) { // Wait for control statements for { select { case msg := <-cons.queue: cons.logRouter.Enqueue(msg) case command := <-cons.control: if command == PluginControlStopConsumer { cons.queue.Close() for msg := range cons.queue { cons.logRouter.Enqueue(msg) } cons.stopped = true return // ### return ### } } } }
[ "func", "(", "cons", "*", "LogConsumer", ")", "Consume", "(", "threads", "*", "sync", ".", "WaitGroup", ")", "{", "// Wait for control statements", "for", "{", "select", "{", "case", "msg", ":=", "<-", "cons", ".", "queue", ":", "cons", ".", "logRouter", ".", "Enqueue", "(", "msg", ")", "\n\n", "case", "command", ":=", "<-", "cons", ".", "control", ":", "if", "command", "==", "PluginControlStopConsumer", "{", "cons", ".", "queue", ".", "Close", "(", ")", "\n", "for", "msg", ":=", "range", "cons", ".", "queue", "{", "cons", ".", "logRouter", ".", "Enqueue", "(", "msg", ")", "\n", "}", "\n", "cons", ".", "stopped", "=", "true", "\n", "return", "// ### return ###", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Consume starts listening for control statements
[ "Consume", "starts", "listening", "for", "control", "statements" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/logconsumer.go#L98-L116
142,598
trivago/gollum
contrib/native/kafka/kafkaproducer.go
OnMessageDelivered
func (prod *KafkaProducer) OnMessageDelivered(userdata []byte) { if msg, err := core.DeserializeMessage(userdata); err == nil { prod.storeRTT(msg) } else { prod.Logger.Error(err) } }
go
func (prod *KafkaProducer) OnMessageDelivered(userdata []byte) { if msg, err := core.DeserializeMessage(userdata); err == nil { prod.storeRTT(msg) } else { prod.Logger.Error(err) } }
[ "func", "(", "prod", "*", "KafkaProducer", ")", "OnMessageDelivered", "(", "userdata", "[", "]", "byte", ")", "{", "if", "msg", ",", "err", ":=", "core", ".", "DeserializeMessage", "(", "userdata", ")", ";", "err", "==", "nil", "{", "prod", ".", "storeRTT", "(", "msg", ")", "\n", "}", "else", "{", "prod", ".", "Logger", ".", "Error", "(", "err", ")", "\n", "}", "\n", "}" ]
// OnMessageDelivered gets called by librdkafka on message delivery success
[ "OnMessageDelivered", "gets", "called", "by", "librdkafka", "on", "message", "delivery", "success" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/kafkaproducer.go#L383-L389
142,599
trivago/gollum
contrib/native/kafka/kafkaproducer.go
OnMessageError
func (prod *KafkaProducer) OnMessageError(reason string, userdata []byte) { prod.Logger.Error("Message delivery failed:", reason) if msg, err := core.DeserializeMessage(userdata); err == nil { prod.storeRTT(msg) prod.TryFallback(msg) } else { prod.Logger.Error(err) } }
go
func (prod *KafkaProducer) OnMessageError(reason string, userdata []byte) { prod.Logger.Error("Message delivery failed:", reason) if msg, err := core.DeserializeMessage(userdata); err == nil { prod.storeRTT(msg) prod.TryFallback(msg) } else { prod.Logger.Error(err) } }
[ "func", "(", "prod", "*", "KafkaProducer", ")", "OnMessageError", "(", "reason", "string", ",", "userdata", "[", "]", "byte", ")", "{", "prod", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "reason", ")", "\n", "if", "msg", ",", "err", ":=", "core", ".", "DeserializeMessage", "(", "userdata", ")", ";", "err", "==", "nil", "{", "prod", ".", "storeRTT", "(", "msg", ")", "\n", "prod", ".", "TryFallback", "(", "msg", ")", "\n", "}", "else", "{", "prod", ".", "Logger", ".", "Error", "(", "err", ")", "\n", "}", "\n", "}" ]
// OnMessageError gets called by librdkafka on message delivery failure
[ "OnMessageError", "gets", "called", "by", "librdkafka", "on", "message", "delivery", "failure" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/kafkaproducer.go#L392-L400