repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
trivago/gollum
coordinator.go
Configure
func (co *Coordinator) Configure(conf *core.Config) error { // Make sure the log is printed to the fallback device if we are stuck here logFallback := time.AfterFunc(time.Duration(3)*time.Second, func() { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() }) defer logFallback.Stop() // Initialize the plugins in the order of routers > producers > consumers // to match the order of reference between the different types. errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) if !co.configureRouters(conf) { errors.Pushf("At least one router failed to be configured") } if !co.configureProducers(conf) { errors.Pushf("At least one producer failed to be configured") } if !co.configureConsumers(conf) { errors.Pushf("At least one consumer failed to be configured") } if len(co.producers) == 0 { errors.Pushf("No valid producers found") } if len(co.consumers) <= 1 { errors.Pushf("No valid consumers found") } // As consumers might create new fallback router this is the first position // where we can add the wildcard producers to all streams. No new routers // created beyond this point must use StreamRegistry.AddWildcardProducersToRouter. core.StreamRegistry.AddAllWildcardProducersToAllRouters() return errors.OrNil() }
go
func (co *Coordinator) Configure(conf *core.Config) error { // Make sure the log is printed to the fallback device if we are stuck here logFallback := time.AfterFunc(time.Duration(3)*time.Second, func() { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() }) defer logFallback.Stop() // Initialize the plugins in the order of routers > producers > consumers // to match the order of reference between the different types. errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) if !co.configureRouters(conf) { errors.Pushf("At least one router failed to be configured") } if !co.configureProducers(conf) { errors.Pushf("At least one producer failed to be configured") } if !co.configureConsumers(conf) { errors.Pushf("At least one consumer failed to be configured") } if len(co.producers) == 0 { errors.Pushf("No valid producers found") } if len(co.consumers) <= 1 { errors.Pushf("No valid consumers found") } // As consumers might create new fallback router this is the first position // where we can add the wildcard producers to all streams. No new routers // created beyond this point must use StreamRegistry.AddWildcardProducersToRouter. core.StreamRegistry.AddAllWildcardProducersToAllRouters() return errors.OrNil() }
[ "func", "(", "co", "*", "Coordinator", ")", "Configure", "(", "conf", "*", "core", ".", "Config", ")", "error", "{", "// Make sure the log is printed to the fallback device if we are stuck here", "logFallback", ":=", "time", ".", "AfterFunc", "(", "time", ".", "Duration", "(", "3", ")", "*", "time", ".", "Second", ",", "func", "(", ")", "{", "logrusHookBuffer", ".", "SetTargetWriter", "(", "logger", ".", "FallbackLogDevice", ")", "\n", "logrusHookBuffer", ".", "Purge", "(", ")", "\n", "}", ")", "\n", "defer", "logFallback", ".", "Stop", "(", ")", "\n\n", "// Initialize the plugins in the order of routers > producers > consumers", "// to match the order of reference between the different types.", "errors", ":=", "tgo", ".", "NewErrorStack", "(", ")", "\n", "errors", ".", "SetFormat", "(", "tgo", ".", "ErrorStackFormatCSV", ")", "\n\n", "if", "!", "co", ".", "configureRouters", "(", "conf", ")", "{", "errors", ".", "Pushf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "co", ".", "configureProducers", "(", "conf", ")", "{", "errors", ".", "Pushf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "co", ".", "configureConsumers", "(", "conf", ")", "{", "errors", ".", "Pushf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "co", ".", "producers", ")", "==", "0", "{", "errors", ".", "Pushf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "co", ".", "consumers", ")", "<=", "1", "{", "errors", ".", "Pushf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// As consumers might create new fallback router this is the first position", "// where we can add the wildcard producers to all streams. No new routers", "// created beyond this point must use StreamRegistry.AddWildcardProducersToRouter.", "core", ".", "StreamRegistry", ".", "AddAllWildcardProducersToAllRouters", "(", ")", "\n", "return", "errors", ".", "OrNil", "(", ")", "\n", "}" ]
// Configure processes the config and instantiates all valid plugins
[ "Configure", "processes", "the", "config", "and", "instantiates", "all", "valid", "plugins" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/coordinator.go#L73-L108
train
trivago/gollum
coordinator.go
StartPlugins
func (co *Coordinator) StartPlugins() { // Launch routers for _, router := range co.routers { logrus.Debug("Starting ", reflect.TypeOf(router)) if err := router.Start(); err != nil { logrus.WithError(err).Errorf("Failed to start router of type '%s'", reflect.TypeOf(router)) } } // Launch producers co.state = coordinatorStateStartProducers for _, producer := range co.producers { producer := producer go tgo.WithRecoverShutdown(func() { logrus.Debug("Starting ", reflect.TypeOf(producer)) producer.Produce(co.producerWorker) }) } // Set final log target and purge the intermediate buffer if core.StreamRegistry.IsStreamRegistered(core.LogInternalStreamID) { // The _GOLLUM_ stream has listeners, so use LogConsumer to write to it if *flagLogColors == "always" { logrus.SetFormatter(logger.NewConsoleFormatter()) } logrusHookBuffer.SetTargetHook(co.logConsumer) logrusHookBuffer.Purge() } else { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() } // Launch consumers co.state = coordinatorStateStartConsumers for _, consumer := range co.consumers { consumer := consumer go tgo.WithRecoverShutdown(func() { logrus.Debug("Starting ", reflect.TypeOf(consumer)) consumer.Consume(co.consumerWorker) }) } }
go
func (co *Coordinator) StartPlugins() { // Launch routers for _, router := range co.routers { logrus.Debug("Starting ", reflect.TypeOf(router)) if err := router.Start(); err != nil { logrus.WithError(err).Errorf("Failed to start router of type '%s'", reflect.TypeOf(router)) } } // Launch producers co.state = coordinatorStateStartProducers for _, producer := range co.producers { producer := producer go tgo.WithRecoverShutdown(func() { logrus.Debug("Starting ", reflect.TypeOf(producer)) producer.Produce(co.producerWorker) }) } // Set final log target and purge the intermediate buffer if core.StreamRegistry.IsStreamRegistered(core.LogInternalStreamID) { // The _GOLLUM_ stream has listeners, so use LogConsumer to write to it if *flagLogColors == "always" { logrus.SetFormatter(logger.NewConsoleFormatter()) } logrusHookBuffer.SetTargetHook(co.logConsumer) logrusHookBuffer.Purge() } else { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() } // Launch consumers co.state = coordinatorStateStartConsumers for _, consumer := range co.consumers { consumer := consumer go tgo.WithRecoverShutdown(func() { logrus.Debug("Starting ", reflect.TypeOf(consumer)) consumer.Consume(co.consumerWorker) }) } }
[ "func", "(", "co", "*", "Coordinator", ")", "StartPlugins", "(", ")", "{", "// Launch routers", "for", "_", ",", "router", ":=", "range", "co", ".", "routers", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "router", ")", ")", "\n", "if", "err", ":=", "router", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "router", ")", ")", "\n", "}", "\n", "}", "\n\n", "// Launch producers", "co", ".", "state", "=", "coordinatorStateStartProducers", "\n", "for", "_", ",", "producer", ":=", "range", "co", ".", "producers", "{", "producer", ":=", "producer", "\n", "go", "tgo", ".", "WithRecoverShutdown", "(", "func", "(", ")", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "producer", ")", ")", "\n", "producer", ".", "Produce", "(", "co", ".", "producerWorker", ")", "\n", "}", ")", "\n", "}", "\n\n", "// Set final log target and purge the intermediate buffer", "if", "core", ".", "StreamRegistry", ".", "IsStreamRegistered", "(", "core", ".", "LogInternalStreamID", ")", "{", "// The _GOLLUM_ stream has listeners, so use LogConsumer to write to it", "if", "*", "flagLogColors", "==", "\"", "\"", "{", "logrus", ".", "SetFormatter", "(", "logger", ".", "NewConsoleFormatter", "(", ")", ")", "\n", "}", "\n", "logrusHookBuffer", ".", "SetTargetHook", "(", "co", ".", "logConsumer", ")", "\n", "logrusHookBuffer", ".", "Purge", "(", ")", "\n\n", "}", "else", "{", "logrusHookBuffer", ".", "SetTargetWriter", "(", "logger", ".", "FallbackLogDevice", ")", "\n", "logrusHookBuffer", ".", "Purge", "(", ")", "\n", "}", "\n\n", "// Launch consumers", "co", ".", "state", "=", "coordinatorStateStartConsumers", "\n", "for", "_", ",", "consumer", ":=", "range", "co", ".", "consumers", "{", "consumer", ":=", "consumer", "\n", "go", "tgo", ".", "WithRecoverShutdown", "(", "func", "(", ")", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "consumer", ")", ")", "\n", "consumer", ".", "Consume", "(", "co", ".", "consumerWorker", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// StartPlugins starts all plugins in the correct order.
[ "StartPlugins", "starts", "all", "plugins", "in", "the", "correct", "order", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/coordinator.go#L111-L153
train
trivago/gollum
coordinator.go
Run
func (co *Coordinator) Run() { co.signal = newSignalHandler() defer signal.Stop(co.signal) logrus.Info("We be nice to them, if they be nice to us. (startup)") for { sig := <-co.signal switch translateSignal(sig) { case signalExit: logrus.Info("Master betrayed us. Wicked. Tricksy, False. (signal)") return // ### return, exit requested ### case signalRoll: for _, consumer := range co.consumers { consumer.Control() <- core.PluginControlRoll } for _, producer := range co.producers { producer.Control() <- core.PluginControlRoll } default: } } }
go
func (co *Coordinator) Run() { co.signal = newSignalHandler() defer signal.Stop(co.signal) logrus.Info("We be nice to them, if they be nice to us. (startup)") for { sig := <-co.signal switch translateSignal(sig) { case signalExit: logrus.Info("Master betrayed us. Wicked. Tricksy, False. (signal)") return // ### return, exit requested ### case signalRoll: for _, consumer := range co.consumers { consumer.Control() <- core.PluginControlRoll } for _, producer := range co.producers { producer.Control() <- core.PluginControlRoll } default: } } }
[ "func", "(", "co", "*", "Coordinator", ")", "Run", "(", ")", "{", "co", ".", "signal", "=", "newSignalHandler", "(", ")", "\n", "defer", "signal", ".", "Stop", "(", "co", ".", "signal", ")", "\n\n", "logrus", ".", "Info", "(", "\"", "\"", ")", "\n\n", "for", "{", "sig", ":=", "<-", "co", ".", "signal", "\n", "switch", "translateSignal", "(", "sig", ")", "{", "case", "signalExit", ":", "logrus", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "// ### return, exit requested ###", "\n\n", "case", "signalRoll", ":", "for", "_", ",", "consumer", ":=", "range", "co", ".", "consumers", "{", "consumer", ".", "Control", "(", ")", "<-", "core", ".", "PluginControlRoll", "\n", "}", "\n", "for", "_", ",", "producer", ":=", "range", "co", ".", "producers", "{", "producer", ".", "Control", "(", ")", "<-", "core", ".", "PluginControlRoll", "\n", "}", "\n\n", "default", ":", "}", "\n", "}", "\n", "}" ]
// Run is essentially the Coordinator main loop. // It listens for shutdown signals and updates global metrics
[ "Run", "is", "essentially", "the", "Coordinator", "main", "loop", ".", "It", "listens", "for", "shutdown", "signals", "and", "updates", "global", "metrics" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/coordinator.go#L157-L181
train
trivago/gollum
coordinator.go
Shutdown
func (co *Coordinator) Shutdown() { logrus.Info("Filthy little hobbites. They stole it from us. (shutdown)") stateAtShutdown := co.state co.state = coordinatorStateShutdown co.shutdownConsumers(stateAtShutdown) // Make sure remaining warning / errors are written to stderr logrus.Info("I'm not listening... I'm not listening... (flushing)") logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.SetTargetHook(nil) logrusHookBuffer.Purge() // Shutdown producers co.shutdownProducers(stateAtShutdown) co.state = coordinatorStateStopped }
go
func (co *Coordinator) Shutdown() { logrus.Info("Filthy little hobbites. They stole it from us. (shutdown)") stateAtShutdown := co.state co.state = coordinatorStateShutdown co.shutdownConsumers(stateAtShutdown) // Make sure remaining warning / errors are written to stderr logrus.Info("I'm not listening... I'm not listening... (flushing)") logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.SetTargetHook(nil) logrusHookBuffer.Purge() // Shutdown producers co.shutdownProducers(stateAtShutdown) co.state = coordinatorStateStopped }
[ "func", "(", "co", "*", "Coordinator", ")", "Shutdown", "(", ")", "{", "logrus", ".", "Info", "(", "\"", "\"", ")", "\n\n", "stateAtShutdown", ":=", "co", ".", "state", "\n", "co", ".", "state", "=", "coordinatorStateShutdown", "\n\n", "co", ".", "shutdownConsumers", "(", "stateAtShutdown", ")", "\n\n", "// Make sure remaining warning / errors are written to stderr", "logrus", ".", "Info", "(", "\"", "\"", ")", "\n", "logrusHookBuffer", ".", "SetTargetWriter", "(", "logger", ".", "FallbackLogDevice", ")", "\n", "logrusHookBuffer", ".", "SetTargetHook", "(", "nil", ")", "\n", "logrusHookBuffer", ".", "Purge", "(", ")", "\n\n", "// Shutdown producers", "co", ".", "shutdownProducers", "(", "stateAtShutdown", ")", "\n\n", "co", ".", "state", "=", "coordinatorStateStopped", "\n", "}" ]
// Shutdown all consumers and producers in a clean way. // The internal log is flushed after the consumers have been shut down so that // consumer related messages are still in the tlog. // Producers are flushed after flushing the log, so producer related shutdown // messages will be posted to stdout
[ "Shutdown", "all", "consumers", "and", "producers", "in", "a", "clean", "way", ".", "The", "internal", "log", "is", "flushed", "after", "the", "consumers", "have", "been", "shut", "down", "so", "that", "consumer", "related", "messages", "are", "still", "in", "the", "tlog", ".", "Producers", "are", "flushed", "after", "flushing", "the", "log", "so", "producer", "related", "shutdown", "messages", "will", "be", "posted", "to", "stdout" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/coordinator.go#L188-L206
train
trivago/gollum
core/simplerouter.go
Configure
func (router *SimpleRouter) Configure(conf PluginConfigReader) { router.id = conf.GetID() router.Logger = conf.GetLogger() if router.streamID == WildcardStreamID && strings.Index(router.id, GeneratedRouterPrefix) != 0 { router.Logger.Info("A wildcard stream configuration only affects the wildcard stream, not all routers") } }
go
func (router *SimpleRouter) Configure(conf PluginConfigReader) { router.id = conf.GetID() router.Logger = conf.GetLogger() if router.streamID == WildcardStreamID && strings.Index(router.id, GeneratedRouterPrefix) != 0 { router.Logger.Info("A wildcard stream configuration only affects the wildcard stream, not all routers") } }
[ "func", "(", "router", "*", "SimpleRouter", ")", "Configure", "(", "conf", "PluginConfigReader", ")", "{", "router", ".", "id", "=", "conf", ".", "GetID", "(", ")", "\n", "router", ".", "Logger", "=", "conf", ".", "GetLogger", "(", ")", "\n\n", "if", "router", ".", "streamID", "==", "WildcardStreamID", "&&", "strings", ".", "Index", "(", "router", ".", "id", ",", "GeneratedRouterPrefix", ")", "!=", "0", "{", "router", ".", "Logger", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Configure sets up all values required by SimpleRouter.
[ "Configure", "sets", "up", "all", "values", "required", "by", "SimpleRouter", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simplerouter.go#L51-L58
train
trivago/gollum
core/simplerouter.go
AddProducer
func (router *SimpleRouter) AddProducer(producers ...Producer) { for _, prod := range producers { for _, inListProd := range router.Producers { if inListProd == prod { return // ### return, already in list ### } } router.Producers = append(router.Producers, prod) } }
go
func (router *SimpleRouter) AddProducer(producers ...Producer) { for _, prod := range producers { for _, inListProd := range router.Producers { if inListProd == prod { return // ### return, already in list ### } } router.Producers = append(router.Producers, prod) } }
[ "func", "(", "router", "*", "SimpleRouter", ")", "AddProducer", "(", "producers", "...", "Producer", ")", "{", "for", "_", ",", "prod", ":=", "range", "producers", "{", "for", "_", ",", "inListProd", ":=", "range", "router", ".", "Producers", "{", "if", "inListProd", "==", "prod", "{", "return", "// ### return, already in list ###", "\n", "}", "\n", "}", "\n", "router", ".", "Producers", "=", "append", "(", "router", ".", "Producers", ",", "prod", ")", "\n", "}", "\n", "}" ]
// AddProducer adds all producers to the list of known producers. // Duplicates will be filtered.
[ "AddProducer", "adds", "all", "producers", "to", "the", "list", "of", "known", "producers", ".", "Duplicates", "will", "be", "filtered", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simplerouter.go#L92-L101
train
trivago/gollum
core/simplerouter.go
Modulate
func (router *SimpleRouter) Modulate(msg *Message) ModulateResult { mod := NewFilterModulator(router.filters) return mod.Modulate(msg) }
go
func (router *SimpleRouter) Modulate(msg *Message) ModulateResult { mod := NewFilterModulator(router.filters) return mod.Modulate(msg) }
[ "func", "(", "router", "*", "SimpleRouter", ")", "Modulate", "(", "msg", "*", "Message", ")", "ModulateResult", "{", "mod", ":=", "NewFilterModulator", "(", "router", ".", "filters", ")", "\n", "return", "mod", ".", "Modulate", "(", "msg", ")", "\n", "}" ]
// Modulate calls all modulators in their order of definition
[ "Modulate", "calls", "all", "modulators", "in", "their", "order", "of", "definition" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simplerouter.go#L109-L112
train
trivago/gollum
producer/awss3/batchedFileWriter.go
init
func (w *BatchedFileWriter) init() { w.totalSize = 0 w.currentMultiPart = 0 w.completedParts = []*s3.CompletedPart{} w.activeBuffer = newS3ByteBuffer() w.createMultipartUpload() }
go
func (w *BatchedFileWriter) init() { w.totalSize = 0 w.currentMultiPart = 0 w.completedParts = []*s3.CompletedPart{} w.activeBuffer = newS3ByteBuffer() w.createMultipartUpload() }
[ "func", "(", "w", "*", "BatchedFileWriter", ")", "init", "(", ")", "{", "w", ".", "totalSize", "=", "0", "\n", "w", ".", "currentMultiPart", "=", "0", "\n", "w", ".", "completedParts", "=", "[", "]", "*", "s3", ".", "CompletedPart", "{", "}", "\n", "w", ".", "activeBuffer", "=", "newS3ByteBuffer", "(", ")", "\n\n", "w", ".", "createMultipartUpload", "(", ")", "\n", "}" ]
// init BatchedFileWriter struct
[ "init", "BatchedFileWriter", "struct" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awss3/batchedFileWriter.go#L78-L85
train
trivago/gollum
core/pluginregistry.go
GetPlugin
func (registry *pluginRegistry) GetPlugin(ID string) Plugin { registry.guard.RLock() plugin, exists := registry.plugins[ID] registry.guard.RUnlock() if exists { return plugin } return nil }
go
func (registry *pluginRegistry) GetPlugin(ID string) Plugin { registry.guard.RLock() plugin, exists := registry.plugins[ID] registry.guard.RUnlock() if exists { return plugin } return nil }
[ "func", "(", "registry", "*", "pluginRegistry", ")", "GetPlugin", "(", "ID", "string", ")", "Plugin", "{", "registry", ".", "guard", ".", "RLock", "(", ")", "\n", "plugin", ",", "exists", ":=", "registry", ".", "plugins", "[", "ID", "]", "\n", "registry", ".", "guard", ".", "RUnlock", "(", ")", "\n\n", "if", "exists", "{", "return", "plugin", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetPlugin returns a plugin by name or nil if not found.
[ "GetPlugin", "returns", "a", "plugin", "by", "name", "or", "nil", "if", "not", "found", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginregistry.go#L47-L56
train
trivago/gollum
core/pluginregistry.go
GetPluginWithState
func (registry *pluginRegistry) GetPluginWithState(ID string) PluginWithState { plugin := registry.GetPlugin(ID) if pluginWithState, hasState := plugin.(PluginWithState); hasState { return pluginWithState } return nil }
go
func (registry *pluginRegistry) GetPluginWithState(ID string) PluginWithState { plugin := registry.GetPlugin(ID) if pluginWithState, hasState := plugin.(PluginWithState); hasState { return pluginWithState } return nil }
[ "func", "(", "registry", "*", "pluginRegistry", ")", "GetPluginWithState", "(", "ID", "string", ")", "PluginWithState", "{", "plugin", ":=", "registry", ".", "GetPlugin", "(", "ID", ")", "\n", "if", "pluginWithState", ",", "hasState", ":=", "plugin", ".", "(", "PluginWithState", ")", ";", "hasState", "{", "return", "pluginWithState", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetPluginWithState returns a plugin by name if it has a state or nil.
[ "GetPluginWithState", "returns", "a", "plugin", "by", "name", "if", "it", "has", "a", "state", "or", "nil", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginregistry.go#L59-L65
train
trivago/gollum
core/messagebatch.go
AppendOrBlock
func (batch *MessageBatch) AppendOrBlock(msg *Message) bool { spin := tsync.NewSpinner(tsync.SpinPriorityMedium) for !batch.IsClosed() { if batch.Append(msg) { return true // ### return, success ### } spin.Yield() } return false }
go
func (batch *MessageBatch) AppendOrBlock(msg *Message) bool { spin := tsync.NewSpinner(tsync.SpinPriorityMedium) for !batch.IsClosed() { if batch.Append(msg) { return true // ### return, success ### } spin.Yield() } return false }
[ "func", "(", "batch", "*", "MessageBatch", ")", "AppendOrBlock", "(", "msg", "*", "Message", ")", "bool", "{", "spin", ":=", "tsync", ".", "NewSpinner", "(", "tsync", ".", "SpinPriorityMedium", ")", "\n", "for", "!", "batch", ".", "IsClosed", "(", ")", "{", "if", "batch", ".", "Append", "(", "msg", ")", "{", "return", "true", "// ### return, success ###", "\n", "}", "\n", "spin", ".", "Yield", "(", ")", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// AppendOrBlock works like Append but will block until Append returns true. // If the batch was closed during this call, false is returned.
[ "AppendOrBlock", "works", "like", "Append", "but", "will", "block", "until", "Append", "returns", "true", ".", "If", "the", "batch", "was", "closed", "during", "this", "call", "false", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L110-L120
train
trivago/gollum
core/messagebatch.go
Touch
func (batch *MessageBatch) Touch() { atomic.StoreInt64(batch.lastFlush, time.Now().Unix()) }
go
func (batch *MessageBatch) Touch() { atomic.StoreInt64(batch.lastFlush, time.Now().Unix()) }
[ "func", "(", "batch", "*", "MessageBatch", ")", "Touch", "(", ")", "{", "atomic", ".", "StoreInt64", "(", "batch", ".", "lastFlush", ",", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", "\n", "}" ]
// Touch resets the timer queried by ReachedTimeThreshold, i.e. this resets the // automatic flush timeout
[ "Touch", "resets", "the", "timer", "queried", "by", "ReachedTimeThreshold", "i", ".", "e", ".", "this", "resets", "the", "automatic", "flush", "timeout" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L137-L139
train
trivago/gollum
core/messagebatch.go
Close
func (batch *MessageBatch) Close(assemble AssemblyFunc, timeout time.Duration) { atomic.StoreInt32(batch.closed, 1) batch.Flush(assemble) batch.WaitForFlush(timeout) }
go
func (batch *MessageBatch) Close(assemble AssemblyFunc, timeout time.Duration) { atomic.StoreInt32(batch.closed, 1) batch.Flush(assemble) batch.WaitForFlush(timeout) }
[ "func", "(", "batch", "*", "MessageBatch", ")", "Close", "(", "assemble", "AssemblyFunc", ",", "timeout", "time", ".", "Duration", ")", "{", "atomic", ".", "StoreInt32", "(", "batch", ".", "closed", ",", "1", ")", "\n", "batch", ".", "Flush", "(", "assemble", ")", "\n", "batch", ".", "WaitForFlush", "(", "timeout", ")", "\n", "}" ]
// Close disables Append, calls flush and waits for this call to finish. // Timeout is passed to WaitForFlush.
[ "Close", "disables", "Append", "calls", "flush", "and", "waits", "for", "this", "call", "to", "finish", ".", "Timeout", "is", "passed", "to", "WaitForFlush", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L143-L147
train
trivago/gollum
core/messagebatch.go
AfterFlushDo
func (batch *MessageBatch) AfterFlushDo(callback func() error) error { batch.flushing.IncWhenDone() defer batch.flushing.Done() return callback() }
go
func (batch *MessageBatch) AfterFlushDo(callback func() error) error { batch.flushing.IncWhenDone() defer batch.flushing.Done() return callback() }
[ "func", "(", "batch", "*", "MessageBatch", ")", "AfterFlushDo", "(", "callback", "func", "(", ")", "error", ")", "error", "{", "batch", ".", "flushing", ".", "IncWhenDone", "(", ")", "\n", "defer", "batch", ".", "flushing", ".", "Done", "(", ")", "\n", "return", "callback", "(", ")", "\n", "}" ]
// AfterFlushDo calls a function after a currently running flush is done. // It also blocks any flush during the execution of callback. // Returns the error returned by callback
[ "AfterFlushDo", "calls", "a", "function", "after", "a", "currently", "running", "flush", "is", "done", ".", "It", "also", "blocks", "any", "flush", "during", "the", "execution", "of", "callback", ".", "Returns", "the", "error", "returned", "by", "callback" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L201-L205
train
trivago/gollum
core/messagebatch.go
WaitForFlush
func (batch *MessageBatch) WaitForFlush(timeout time.Duration) { batch.flushing.WaitFor(timeout) }
go
func (batch *MessageBatch) WaitForFlush(timeout time.Duration) { batch.flushing.WaitFor(timeout) }
[ "func", "(", "batch", "*", "MessageBatch", ")", "WaitForFlush", "(", "timeout", "time", ".", "Duration", ")", "{", "batch", ".", "flushing", ".", "WaitFor", "(", "timeout", ")", "\n", "}" ]
// WaitForFlush blocks until the current flush command returns. // Passing a timeout > 0 will unblock this function after the given duration at // the latest.
[ "WaitForFlush", "blocks", "until", "the", "current", "flush", "command", "returns", ".", "Passing", "a", "timeout", ">", "0", "will", "unblock", "this", "function", "after", "the", "given", "duration", "at", "the", "latest", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L210-L212
train
trivago/gollum
core/messagebatch.go
ReachedSizeThreshold
func (batch MessageBatch) ReachedSizeThreshold(size int) bool { activeIdx := atomic.LoadUint32(batch.activeSet) >> messageBatchIndexShift threshold := uint32(tmath.MaxI(size, len(batch.queue[activeIdx].messages))) return atomic.LoadUint32(batch.queue[activeIdx].doneCount) >= threshold }
go
func (batch MessageBatch) ReachedSizeThreshold(size int) bool { activeIdx := atomic.LoadUint32(batch.activeSet) >> messageBatchIndexShift threshold := uint32(tmath.MaxI(size, len(batch.queue[activeIdx].messages))) return atomic.LoadUint32(batch.queue[activeIdx].doneCount) >= threshold }
[ "func", "(", "batch", "MessageBatch", ")", "ReachedSizeThreshold", "(", "size", "int", ")", "bool", "{", "activeIdx", ":=", "atomic", ".", "LoadUint32", "(", "batch", ".", "activeSet", ")", ">>", "messageBatchIndexShift", "\n", "threshold", ":=", "uint32", "(", "tmath", ".", "MaxI", "(", "size", ",", "len", "(", "batch", ".", "queue", "[", "activeIdx", "]", ".", "messages", ")", ")", ")", "\n", "return", "atomic", ".", "LoadUint32", "(", "batch", ".", "queue", "[", "activeIdx", "]", ".", "doneCount", ")", ">=", "threshold", "\n", "}" ]
// ReachedSizeThreshold returns true if the bytes stored in the buffer are // above or equal to the size given. // If there is no data this function returns false.
[ "ReachedSizeThreshold", "returns", "true", "if", "the", "bytes", "stored", "in", "the", "buffer", "are", "above", "or", "equal", "to", "the", "size", "given", ".", "If", "there", "is", "no", "data", "this", "function", "returns", "false", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L223-L227
train
trivago/gollum
core/messagebatch.go
ReachedTimeThreshold
func (batch MessageBatch) ReachedTimeThreshold(timeout time.Duration) bool { lastFlush := time.Unix(atomic.LoadInt64(batch.lastFlush), 0) return !batch.IsEmpty() && time.Since(lastFlush) > timeout }
go
func (batch MessageBatch) ReachedTimeThreshold(timeout time.Duration) bool { lastFlush := time.Unix(atomic.LoadInt64(batch.lastFlush), 0) return !batch.IsEmpty() && time.Since(lastFlush) > timeout }
[ "func", "(", "batch", "MessageBatch", ")", "ReachedTimeThreshold", "(", "timeout", "time", ".", "Duration", ")", "bool", "{", "lastFlush", ":=", "time", ".", "Unix", "(", "atomic", ".", "LoadInt64", "(", "batch", ".", "lastFlush", ")", ",", "0", ")", "\n", "return", "!", "batch", ".", "IsEmpty", "(", ")", "&&", "time", ".", "Since", "(", "lastFlush", ")", ">", "timeout", "\n", "}" ]
// ReachedTimeThreshold returns true if the last flush was more than timeout ago. // If there is no data this function returns false.
[ "ReachedTimeThreshold", "returns", "true", "if", "the", "last", "flush", "was", "more", "than", "timeout", "ago", ".", "If", "there", "is", "no", "data", "this", "function", "returns", "false", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L231-L234
train
trivago/gollum
core/config.go
ReadConfig
func ReadConfig(buffer []byte) (*Config, error) { config := new(Config) if err := yaml.Unmarshal(buffer, &config.Values); err != nil { return nil, err } // As there might be multiple instances of the same plugin class we iterate // over an array here. hasError := false for pluginID, configValues := range config.Values { if typeName, _ := configValues.String("Type"); typeName == pluginAggregate { // aggregate behavior aggregateMap, err := configValues.MarshalMap("Plugins") if err != nil { hasError = true logrus.Error("Can't read 'Aggregate' configuration: ", err) continue } // loop through aggregated plugins and set them up for subPluginID, subConfigValues := range aggregateMap { subPluginsID := fmt.Sprintf("%s-%s", pluginID, subPluginID) subConfig, err := tcontainer.ConvertToMarshalMap(subConfigValues, nil) if err != nil { hasError = true logrus.Error("Error in plugin config ", subPluginsID, err) continue } // set up sub-plugin delete(configValues, "Type") delete(configValues, "Plugins") pluginConfig := NewPluginConfig(subPluginsID, "") pluginConfig.Read(configValues) pluginConfig.Read(subConfig) config.Plugins = append(config.Plugins, pluginConfig) } } else { // default behavior pluginConfig := NewPluginConfig(pluginID, "") pluginConfig.Read(configValues) config.Plugins = append(config.Plugins, pluginConfig) } } if hasError { return config, fmt.Errorf("configuration parsing produced errors") } return config, nil }
go
func ReadConfig(buffer []byte) (*Config, error) { config := new(Config) if err := yaml.Unmarshal(buffer, &config.Values); err != nil { return nil, err } // As there might be multiple instances of the same plugin class we iterate // over an array here. hasError := false for pluginID, configValues := range config.Values { if typeName, _ := configValues.String("Type"); typeName == pluginAggregate { // aggregate behavior aggregateMap, err := configValues.MarshalMap("Plugins") if err != nil { hasError = true logrus.Error("Can't read 'Aggregate' configuration: ", err) continue } // loop through aggregated plugins and set them up for subPluginID, subConfigValues := range aggregateMap { subPluginsID := fmt.Sprintf("%s-%s", pluginID, subPluginID) subConfig, err := tcontainer.ConvertToMarshalMap(subConfigValues, nil) if err != nil { hasError = true logrus.Error("Error in plugin config ", subPluginsID, err) continue } // set up sub-plugin delete(configValues, "Type") delete(configValues, "Plugins") pluginConfig := NewPluginConfig(subPluginsID, "") pluginConfig.Read(configValues) pluginConfig.Read(subConfig) config.Plugins = append(config.Plugins, pluginConfig) } } else { // default behavior pluginConfig := NewPluginConfig(pluginID, "") pluginConfig.Read(configValues) config.Plugins = append(config.Plugins, pluginConfig) } } if hasError { return config, fmt.Errorf("configuration parsing produced errors") } return config, nil }
[ "func", "ReadConfig", "(", "buffer", "[", "]", "byte", ")", "(", "*", "Config", ",", "error", ")", "{", "config", ":=", "new", "(", "Config", ")", "\n", "if", "err", ":=", "yaml", ".", "Unmarshal", "(", "buffer", ",", "&", "config", ".", "Values", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// As there might be multiple instances of the same plugin class we iterate", "// over an array here.", "hasError", ":=", "false", "\n", "for", "pluginID", ",", "configValues", ":=", "range", "config", ".", "Values", "{", "if", "typeName", ",", "_", ":=", "configValues", ".", "String", "(", "\"", "\"", ")", ";", "typeName", "==", "pluginAggregate", "{", "// aggregate behavior", "aggregateMap", ",", "err", ":=", "configValues", ".", "MarshalMap", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "hasError", "=", "true", "\n", "logrus", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "// loop through aggregated plugins and set them up", "for", "subPluginID", ",", "subConfigValues", ":=", "range", "aggregateMap", "{", "subPluginsID", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pluginID", ",", "subPluginID", ")", "\n", "subConfig", ",", "err", ":=", "tcontainer", ".", "ConvertToMarshalMap", "(", "subConfigValues", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "hasError", "=", "true", "\n", "logrus", ".", "Error", "(", "\"", "\"", ",", "subPluginsID", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "// set up sub-plugin", "delete", "(", "configValues", ",", "\"", "\"", ")", "\n", "delete", "(", "configValues", ",", "\"", "\"", ")", "\n\n", "pluginConfig", ":=", "NewPluginConfig", "(", "subPluginsID", ",", "\"", "\"", ")", "\n", "pluginConfig", ".", "Read", "(", "configValues", ")", "\n", "pluginConfig", ".", "Read", "(", "subConfig", ")", "\n\n", "config", ".", "Plugins", "=", "append", "(", "config", ".", "Plugins", ",", "pluginConfig", ")", "\n", "}", "\n", "}", "else", "{", "// default behavior", "pluginConfig", ":=", "NewPluginConfig", "(", "pluginID", ",", "\"", "\"", ")", "\n", "pluginConfig", ".", "Read", "(", "configValues", ")", "\n", "config", ".", "Plugins", "=", "append", "(", "config", ".", "Plugins", ",", "pluginConfig", ")", "\n", "}", "\n", "}", "\n\n", "if", "hasError", "{", "return", "config", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "config", ",", "nil", "\n", "}" ]
// ReadConfig creates a config from a yaml byte stream.
[ "ReadConfig", "creates", "a", "config", "from", "a", "yaml", "byte", "stream", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/config.go#L44-L95
train
trivago/gollum
core/config.go
ReadConfigFromFile
func ReadConfigFromFile(path string) (*Config, error) { buffer, err := ioutil.ReadFile(path) if err != nil { return nil, err } return ReadConfig(buffer) }
go
func ReadConfigFromFile(path string) (*Config, error) { buffer, err := ioutil.ReadFile(path) if err != nil { return nil, err } return ReadConfig(buffer) }
[ "func", "ReadConfigFromFile", "(", "path", "string", ")", "(", "*", "Config", ",", "error", ")", "{", "buffer", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "ReadConfig", "(", "buffer", ")", "\n", "}" ]
// ReadConfigFromFile parses a YAML config file into a new Config struct.
[ "ReadConfigFromFile", "parses", "a", "YAML", "config", "file", "into", "a", "new", "Config", "struct", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/config.go#L98-L105
train
trivago/gollum
core/config.go
Validate
func (conf *Config) Validate() error { errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) for _, config := range conf.Plugins { if config.Typename == "" { errors.Pushf("Plugin type is not set for '%s'", config.ID) continue } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { if suggestion := suggestType(config.Typename); suggestion != "" { errors.Pushf("Type '%s' used for '%s' not found. Did you mean '%s'?", config.Typename, config.ID, suggestion) } else { errors.Pushf("Type '%s' used for '%s' not found", config.Typename, config.ID) } continue // ### continue ### } switch { case pluginType.Implements(consumerInterface): continue case pluginType.Implements(producerInterface): continue case pluginType.Implements(routerInterface): continue } errors.Pushf("Type '%s' used for '%s' does not implement a common interface", config.Typename, config.ID) getClosestMatch(pluginType, &errors) } return errors.OrNil() }
go
func (conf *Config) Validate() error { errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) for _, config := range conf.Plugins { if config.Typename == "" { errors.Pushf("Plugin type is not set for '%s'", config.ID) continue } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { if suggestion := suggestType(config.Typename); suggestion != "" { errors.Pushf("Type '%s' used for '%s' not found. Did you mean '%s'?", config.Typename, config.ID, suggestion) } else { errors.Pushf("Type '%s' used for '%s' not found", config.Typename, config.ID) } continue // ### continue ### } switch { case pluginType.Implements(consumerInterface): continue case pluginType.Implements(producerInterface): continue case pluginType.Implements(routerInterface): continue } errors.Pushf("Type '%s' used for '%s' does not implement a common interface", config.Typename, config.ID) getClosestMatch(pluginType, &errors) } return errors.OrNil() }
[ "func", "(", "conf", "*", "Config", ")", "Validate", "(", ")", "error", "{", "errors", ":=", "tgo", ".", "NewErrorStack", "(", ")", "\n", "errors", ".", "SetFormat", "(", "tgo", ".", "ErrorStackFormatCSV", ")", "\n\n", "for", "_", ",", "config", ":=", "range", "conf", ".", "Plugins", "{", "if", "config", ".", "Typename", "==", "\"", "\"", "{", "errors", ".", "Pushf", "(", "\"", "\"", ",", "config", ".", "ID", ")", "\n", "continue", "\n", "}", "\n\n", "pluginType", ":=", "TypeRegistry", ".", "GetTypeOf", "(", "config", ".", "Typename", ")", "\n", "if", "pluginType", "==", "nil", "{", "if", "suggestion", ":=", "suggestType", "(", "config", ".", "Typename", ")", ";", "suggestion", "!=", "\"", "\"", "{", "errors", ".", "Pushf", "(", "\"", "\"", ",", "config", ".", "Typename", ",", "config", ".", "ID", ",", "suggestion", ")", "\n", "}", "else", "{", "errors", ".", "Pushf", "(", "\"", "\"", ",", "config", ".", "Typename", ",", "config", ".", "ID", ")", "\n", "}", "\n\n", "continue", "// ### continue ###", "\n", "}", "\n\n", "switch", "{", "case", "pluginType", ".", "Implements", "(", "consumerInterface", ")", ":", "continue", "\n\n", "case", "pluginType", ".", "Implements", "(", "producerInterface", ")", ":", "continue", "\n\n", "case", "pluginType", ".", "Implements", "(", "routerInterface", ")", ":", "continue", "\n", "}", "\n\n", "errors", ".", "Pushf", "(", "\"", "\"", ",", "config", ".", "Typename", ",", "config", ".", "ID", ")", "\n", "getClosestMatch", "(", "pluginType", ",", "&", "errors", ")", "\n", "}", "\n\n", "return", "errors", ".", "OrNil", "(", ")", "\n", "}" ]
// Validate checks all plugin configs and plugins on validity. I.e. it checks // on mandatory fields and correct implementation of consumer, producer or // stream interface. It does NOT call configure for each plugin.
[ "Validate", "checks", "all", "plugin", "configs", "and", "plugins", "on", "validity", ".", "I", ".", "e", ".", "it", "checks", "on", "mandatory", "fields", "and", "correct", "implementation", "of", "consumer", "producer", "or", "stream", "interface", ".", "It", "does", "NOT", "call", "configure", "for", "each", "plugin", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/config.go#L110-L147
train
trivago/gollum
core/config.go
GetConsumers
func (conf *Config) GetConsumers() []PluginConfig { configs := []PluginConfig{} for _, config := range conf.Plugins { if !config.Enable || config.Typename == "" { continue // ### continue, disabled ### } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { continue // ### continue, unknown type ### } if pluginType.Implements(consumerInterface) { logrus.Debug("Found consumer ", config.ID) configs = append(configs, config) } } return configs }
go
func (conf *Config) GetConsumers() []PluginConfig { configs := []PluginConfig{} for _, config := range conf.Plugins { if !config.Enable || config.Typename == "" { continue // ### continue, disabled ### } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { continue // ### continue, unknown type ### } if pluginType.Implements(consumerInterface) { logrus.Debug("Found consumer ", config.ID) configs = append(configs, config) } } return configs }
[ "func", "(", "conf", "*", "Config", ")", "GetConsumers", "(", ")", "[", "]", "PluginConfig", "{", "configs", ":=", "[", "]", "PluginConfig", "{", "}", "\n\n", "for", "_", ",", "config", ":=", "range", "conf", ".", "Plugins", "{", "if", "!", "config", ".", "Enable", "||", "config", ".", "Typename", "==", "\"", "\"", "{", "continue", "// ### continue, disabled ###", "\n", "}", "\n\n", "pluginType", ":=", "TypeRegistry", ".", "GetTypeOf", "(", "config", ".", "Typename", ")", "\n", "if", "pluginType", "==", "nil", "{", "continue", "// ### continue, unknown type ###", "\n", "}", "\n\n", "if", "pluginType", ".", "Implements", "(", "consumerInterface", ")", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "config", ".", "ID", ")", "\n", "configs", "=", "append", "(", "configs", ",", "config", ")", "\n", "}", "\n", "}", "\n\n", "return", "configs", "\n", "}" ]
// GetConsumers returns all consumer plugins from the config
[ "GetConsumers", "returns", "all", "consumer", "plugins", "from", "the", "config" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/config.go#L150-L170
train
trivago/gollum
core/config.go
GetRouters
func (conf *Config) GetRouters() []PluginConfig { configs := []PluginConfig{} for _, config := range conf.Plugins { if !config.Enable || config.Typename == "" { continue // ### continue, disabled ### } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { continue // ### continue, unknown type ### } if pluginType.Implements(routerInterface) { logrus.Debugf("Found router '%s'", config.ID) configs = append(configs, config) } } return configs }
go
func (conf *Config) GetRouters() []PluginConfig { configs := []PluginConfig{} for _, config := range conf.Plugins { if !config.Enable || config.Typename == "" { continue // ### continue, disabled ### } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { continue // ### continue, unknown type ### } if pluginType.Implements(routerInterface) { logrus.Debugf("Found router '%s'", config.ID) configs = append(configs, config) } } return configs }
[ "func", "(", "conf", "*", "Config", ")", "GetRouters", "(", ")", "[", "]", "PluginConfig", "{", "configs", ":=", "[", "]", "PluginConfig", "{", "}", "\n\n", "for", "_", ",", "config", ":=", "range", "conf", ".", "Plugins", "{", "if", "!", "config", ".", "Enable", "||", "config", ".", "Typename", "==", "\"", "\"", "{", "continue", "// ### continue, disabled ###", "\n", "}", "\n\n", "pluginType", ":=", "TypeRegistry", ".", "GetTypeOf", "(", "config", ".", "Typename", ")", "\n", "if", "pluginType", "==", "nil", "{", "continue", "// ### continue, unknown type ###", "\n", "}", "\n\n", "if", "pluginType", ".", "Implements", "(", "routerInterface", ")", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "config", ".", "ID", ")", "\n", "configs", "=", "append", "(", "configs", ",", "config", ")", "\n", "}", "\n", "}", "\n\n", "return", "configs", "\n", "}" ]
// GetRouters returns all stream plugins from the config
[ "GetRouters", "returns", "all", "stream", "plugins", "from", "the", "config" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/config.go#L196-L216
train
trivago/gollum
contrib/native/kafka/librdkafka/topic.go
Close
func (t *Topic) Close() { oldQueueLen := C.int(0x7FFFFFFF) queueLen := C.rd_kafka_outq_len(t.client.handle) // Wait as long as we're flushing for queueLen > 0 && queueLen < oldQueueLen { C.rd_kafka_poll(t.client.handle, 1000) oldQueueLen = queueLen queueLen = C.rd_kafka_outq_len(t.client.handle) } if queueLen > 0 { Log.Printf("%d messages have been lost as the internal queue for %s could not be flushed", queueLen, t.name) } C.rd_kafka_topic_destroy(t.handle) }
go
func (t *Topic) Close() { oldQueueLen := C.int(0x7FFFFFFF) queueLen := C.rd_kafka_outq_len(t.client.handle) // Wait as long as we're flushing for queueLen > 0 && queueLen < oldQueueLen { C.rd_kafka_poll(t.client.handle, 1000) oldQueueLen = queueLen queueLen = C.rd_kafka_outq_len(t.client.handle) } if queueLen > 0 { Log.Printf("%d messages have been lost as the internal queue for %s could not be flushed", queueLen, t.name) } C.rd_kafka_topic_destroy(t.handle) }
[ "func", "(", "t", "*", "Topic", ")", "Close", "(", ")", "{", "oldQueueLen", ":=", "C", ".", "int", "(", "0x7FFFFFFF", ")", "\n", "queueLen", ":=", "C", ".", "rd_kafka_outq_len", "(", "t", ".", "client", ".", "handle", ")", "\n\n", "// Wait as long as we're flushing", "for", "queueLen", ">", "0", "&&", "queueLen", "<", "oldQueueLen", "{", "C", ".", "rd_kafka_poll", "(", "t", ".", "client", ".", "handle", ",", "1000", ")", "\n", "oldQueueLen", "=", "queueLen", "\n", "queueLen", "=", "C", ".", "rd_kafka_outq_len", "(", "t", ".", "client", ".", "handle", ")", "\n", "}", "\n\n", "if", "queueLen", ">", "0", "{", "Log", ".", "Printf", "(", "\"", "\"", ",", "queueLen", ",", "t", ".", "name", ")", "\n", "}", "\n", "C", ".", "rd_kafka_topic_destroy", "(", "t", ".", "handle", ")", "\n", "}" ]
// Close frees the internal handle and tries to flush the queue.
[ "Close", "frees", "the", "internal", "handle", "and", "tries", "to", "flush", "the", "queue", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/librdkafka/topic.go#L44-L59
train
trivago/gollum
main.go
initLogrus
func initLogrus() func() { // Initialize logger.LogrusHookBuffer logrusHookBuffer = logger.NewLogrusHookBuffer() // Initialize logging. All logging is done via logrusHookBuffer; // logrus's output writer is always set to ioutil.Discard. logrus.AddHook(&logrusHookBuffer) logrus.SetOutput(ioutil.Discard) logrus.SetLevel(getLogrusLevel(*flagLoglevel)) switch *flagLogColors { case "never", "auto", "always": default: fmt.Printf("Invalid parameter for -log-colors: '%s'\n", *flagLogColors) *flagLogColors = "auto" } if *flagLogColors == "always" || (*flagLogColors == "auto" && terminal.IsTerminal(int(logger.FallbackLogDevice.Fd()))) { // Logrus doesn't know the final log device, so we hint the color option here logrus.SetFormatter(logger.NewConsoleFormatter()) } // make sure logs are purged at exit return func() { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() } }
go
func initLogrus() func() { // Initialize logger.LogrusHookBuffer logrusHookBuffer = logger.NewLogrusHookBuffer() // Initialize logging. All logging is done via logrusHookBuffer; // logrus's output writer is always set to ioutil.Discard. logrus.AddHook(&logrusHookBuffer) logrus.SetOutput(ioutil.Discard) logrus.SetLevel(getLogrusLevel(*flagLoglevel)) switch *flagLogColors { case "never", "auto", "always": default: fmt.Printf("Invalid parameter for -log-colors: '%s'\n", *flagLogColors) *flagLogColors = "auto" } if *flagLogColors == "always" || (*flagLogColors == "auto" && terminal.IsTerminal(int(logger.FallbackLogDevice.Fd()))) { // Logrus doesn't know the final log device, so we hint the color option here logrus.SetFormatter(logger.NewConsoleFormatter()) } // make sure logs are purged at exit return func() { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() } }
[ "func", "initLogrus", "(", ")", "func", "(", ")", "{", "// Initialize logger.LogrusHookBuffer", "logrusHookBuffer", "=", "logger", ".", "NewLogrusHookBuffer", "(", ")", "\n\n", "// Initialize logging. All logging is done via logrusHookBuffer;", "// logrus's output writer is always set to ioutil.Discard.", "logrus", ".", "AddHook", "(", "&", "logrusHookBuffer", ")", "\n", "logrus", ".", "SetOutput", "(", "ioutil", ".", "Discard", ")", "\n", "logrus", ".", "SetLevel", "(", "getLogrusLevel", "(", "*", "flagLoglevel", ")", ")", "\n\n", "switch", "*", "flagLogColors", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "default", ":", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "*", "flagLogColors", ")", "\n", "*", "flagLogColors", "=", "\"", "\"", "\n", "}", "\n\n", "if", "*", "flagLogColors", "==", "\"", "\"", "||", "(", "*", "flagLogColors", "==", "\"", "\"", "&&", "terminal", ".", "IsTerminal", "(", "int", "(", "logger", ".", "FallbackLogDevice", ".", "Fd", "(", ")", ")", ")", ")", "{", "// Logrus doesn't know the final log device, so we hint the color option here", "logrus", ".", "SetFormatter", "(", "logger", ".", "NewConsoleFormatter", "(", ")", ")", "\n", "}", "\n\n", "// make sure logs are purged at exit", "return", "func", "(", ")", "{", "logrusHookBuffer", ".", "SetTargetWriter", "(", "logger", ".", "FallbackLogDevice", ")", "\n", "logrusHookBuffer", ".", "Purge", "(", ")", "\n", "}", "\n", "}" ]
// initLogrus initializes the logging framework
[ "initLogrus", "initializes", "the", "logging", "framework" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/main.go#L155-L183
train
trivago/gollum
main.go
readConfig
func readConfig(configFile string) *core.Config { if *flagHelp || configFile == "" { logrus.Error("Please provide a config file") return nil } config, err := core.ReadConfigFromFile(configFile) if err != nil { logrus.WithError(err).Error("Failed to read config") return nil } if err := config.Validate(); err != nil { logrus.WithError(err).Error("Config validation failed") return nil } return config }
go
func readConfig(configFile string) *core.Config { if *flagHelp || configFile == "" { logrus.Error("Please provide a config file") return nil } config, err := core.ReadConfigFromFile(configFile) if err != nil { logrus.WithError(err).Error("Failed to read config") return nil } if err := config.Validate(); err != nil { logrus.WithError(err).Error("Config validation failed") return nil } return config }
[ "func", "readConfig", "(", "configFile", "string", ")", "*", "core", ".", "Config", "{", "if", "*", "flagHelp", "||", "configFile", "==", "\"", "\"", "{", "logrus", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "config", ",", "err", ":=", "core", ".", "ReadConfigFromFile", "(", "configFile", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "return", "config", "\n", "}" ]
// readConfig reads and checks the config file for errors.
[ "readConfig", "reads", "and", "checks", "the", "config", "file", "for", "errors", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/main.go#L186-L204
train
trivago/gollum
main.go
configureRuntime
func configureRuntime() { if *flagPidFile != "" { err := ioutil.WriteFile(*flagPidFile, []byte(strconv.Itoa(os.Getpid())), 0644) if err != nil { logrus.WithError(err).Error("Failed to write pid file") } } if *flagNumCPU == 0 { runtime.GOMAXPROCS(runtime.NumCPU()) } else { runtime.GOMAXPROCS(*flagNumCPU) } if *flagProfile { time.AfterFunc(time.Second*3, printProfile) } if *flagTrace { core.ActivateMessageTrace() } }
go
func configureRuntime() { if *flagPidFile != "" { err := ioutil.WriteFile(*flagPidFile, []byte(strconv.Itoa(os.Getpid())), 0644) if err != nil { logrus.WithError(err).Error("Failed to write pid file") } } if *flagNumCPU == 0 { runtime.GOMAXPROCS(runtime.NumCPU()) } else { runtime.GOMAXPROCS(*flagNumCPU) } if *flagProfile { time.AfterFunc(time.Second*3, printProfile) } if *flagTrace { core.ActivateMessageTrace() } }
[ "func", "configureRuntime", "(", ")", "{", "if", "*", "flagPidFile", "!=", "\"", "\"", "{", "err", ":=", "ioutil", ".", "WriteFile", "(", "*", "flagPidFile", ",", "[", "]", "byte", "(", "strconv", ".", "Itoa", "(", "os", ".", "Getpid", "(", ")", ")", ")", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "*", "flagNumCPU", "==", "0", "{", "runtime", ".", "GOMAXPROCS", "(", "runtime", ".", "NumCPU", "(", ")", ")", "\n", "}", "else", "{", "runtime", ".", "GOMAXPROCS", "(", "*", "flagNumCPU", ")", "\n", "}", "\n\n", "if", "*", "flagProfile", "{", "time", ".", "AfterFunc", "(", "time", ".", "Second", "*", "3", ",", "printProfile", ")", "\n", "}", "\n\n", "if", "*", "flagTrace", "{", "core", ".", "ActivateMessageTrace", "(", ")", "\n", "}", "\n", "}" ]
// configureRuntime does various different settings that affect runtime // behavior or enables global functionality
[ "configureRuntime", "does", "various", "different", "settings", "that", "affect", "runtime", "behavior", "or", "enables", "global", "functionality" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/main.go#L208-L229
train
trivago/gollum
main.go
startMetricsService
func startMetricsService() func() { if *flagMetricsAddress == "" { return nil } address, err := parseAddress(*flagMetricsAddress) if err != nil { logrus.WithError(err).Error("Failed to parse metrics address") return nil } metricsType := "prometheus" if *flagMetricsType != "" { metricsType = strings.ToLower(*flagMetricsType) } switch metricsType { case "prometheus": return startPrometheusMetricsService(address) default: logrus.Errorf("Unknown metrics type: %s", metricsType) return nil } }
go
func startMetricsService() func() { if *flagMetricsAddress == "" { return nil } address, err := parseAddress(*flagMetricsAddress) if err != nil { logrus.WithError(err).Error("Failed to parse metrics address") return nil } metricsType := "prometheus" if *flagMetricsType != "" { metricsType = strings.ToLower(*flagMetricsType) } switch metricsType { case "prometheus": return startPrometheusMetricsService(address) default: logrus.Errorf("Unknown metrics type: %s", metricsType) return nil } }
[ "func", "startMetricsService", "(", ")", "func", "(", ")", "{", "if", "*", "flagMetricsAddress", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "address", ",", "err", ":=", "parseAddress", "(", "*", "flagMetricsAddress", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "metricsType", ":=", "\"", "\"", "\n", "if", "*", "flagMetricsType", "!=", "\"", "\"", "{", "metricsType", "=", "strings", ".", "ToLower", "(", "*", "flagMetricsType", ")", "\n", "}", "\n\n", "switch", "metricsType", "{", "case", "\"", "\"", ":", "return", "startPrometheusMetricsService", "(", "address", ")", "\n\n", "default", ":", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "metricsType", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// startMetricsService creates a metric endpoint if requested. // The returned function should be deferred if not nil.
[ "startMetricsService", "creates", "a", "metric", "endpoint", "if", "requested", ".", "The", "returned", "function", "should", "be", "deferred", "if", "not", "nil", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/main.go#L233-L257
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train