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
core/components/batchedWriterAssembly.go
Close
func (bwa *BatchedWriterAssembly) Close() { if bwa.writer != nil { bwa.assembly.SetWriter(bwa.writer) bwa.Batch.Close(bwa.assembly.Write, bwa.config.BatchFlushTimeout) } else { bwa.Batch.Close(bwa.assembly.Flush, bwa.config.BatchFlushTimeout) } bwa.writer.Close() }
go
func (bwa *BatchedWriterAssembly) Close() { if bwa.writer != nil { bwa.assembly.SetWriter(bwa.writer) bwa.Batch.Close(bwa.assembly.Write, bwa.config.BatchFlushTimeout) } else { bwa.Batch.Close(bwa.assembly.Flush, bwa.config.BatchFlushTimeout) } bwa.writer.Close() }
[ "func", "(", "bwa", "*", "BatchedWriterAssembly", ")", "Close", "(", ")", "{", "if", "bwa", ".", "writer", "!=", "nil", "{", "bwa", ".", "assembly", ".", "SetWriter", "(", "bwa", ".", "writer", ")", "\n", "bwa", ".", "Batch", ".", "Close", "(", "bwa", ".", "assembly", ".", "Write", ",", "bwa", ".", "config", ".", "BatchFlushTimeout", ")", "\n", "}", "else", "{", "bwa", ".", "Batch", ".", "Close", "(", "bwa", ".", "assembly", ".", "Flush", ",", "bwa", ".", "config", ".", "BatchFlushTimeout", ")", "\n", "}", "\n", "bwa", ".", "writer", ".", "Close", "(", ")", "\n", "}" ]
// Close closes batch and writer
[ "Close", "closes", "batch", "and", "writer" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L128-L136
train
trivago/gollum
core/components/batchedWriterAssembly.go
FlushOnTimeOut
func (bwa *BatchedWriterAssembly) FlushOnTimeOut() { if bwa.Batch.ReachedTimeThreshold(bwa.config.BatchTimeout) || bwa.Batch.ReachedSizeThreshold(bwa.config.BatchFlushCount) { bwa.Flush() } }
go
func (bwa *BatchedWriterAssembly) FlushOnTimeOut() { if bwa.Batch.ReachedTimeThreshold(bwa.config.BatchTimeout) || bwa.Batch.ReachedSizeThreshold(bwa.config.BatchFlushCount) { bwa.Flush() } }
[ "func", "(", "bwa", "*", "BatchedWriterAssembly", ")", "FlushOnTimeOut", "(", ")", "{", "if", "bwa", ".", "Batch", ".", "ReachedTimeThreshold", "(", "bwa", ".", "config", ".", "BatchTimeout", ")", "||", "bwa", ".", "Batch", ".", "ReachedSizeThreshold", "(", "bwa", ".", "config", ".", "BatchFlushCount", ")", "{", "bwa", ".", "Flush", "(", ")", "\n", "}", "\n", "}" ]
// FlushOnTimeOut checks if timeout or slush count reached and flush in this case
[ "FlushOnTimeOut", "checks", "if", "timeout", "or", "slush", "count", "reached", "and", "flush", "in", "this", "case" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L139-L143
train
trivago/gollum
core/components/batchedWriterAssembly.go
NeedsRotate
func (bwa *BatchedWriterAssembly) NeedsRotate(rotate RotateConfig, forceRotate bool) (bool, error) { // File does not exist? if !bwa.HasWriter() { bwa.logger.Debug("Rotate true: ", "no writer") return true, nil } // File can be accessed? if !bwa.GetWriter().IsAccessible() { bwa.logger.Debug("Rotate false: ", "no access") return false, errors.New("can' access file to rotate") } // File needs rotation? if !rotate.Enabled { bwa.logger.Debug("Rotate false: ", "not active") return false, nil } if forceRotate { bwa.logger.Debug("Rotate true: ", "forced") return true, nil } // File is too large? if bwa.GetWriter().Size() >= rotate.SizeByte { bwa.logger.Debug("Rotate true: ", "size > rotation size") return true, nil // ### return, too large ### } // File is too old? if time.Since(bwa.Created) >= rotate.Timeout { bwa.logger.Debug("Rotate true: ", "lifetime > timeout setting") return true, nil // ### return, too old ### } // RotateAt crossed? if rotate.AtHour > -1 && rotate.AtMinute > -1 { now := time.Now() rotateAt := time.Date(now.Year(), now.Month(), now.Day(), rotate.AtHour, rotate.AtMinute, 0, 0, now.Location()) if rotateAt.Before(bwa.Created) { return false, nil } if now.After(rotateAt) { bwa.logger.Debug("Rotate true: ", "rotateAt time reached") return true, nil // ### return, too old ### } } // nope, everything is ok return false, nil }
go
func (bwa *BatchedWriterAssembly) NeedsRotate(rotate RotateConfig, forceRotate bool) (bool, error) { // File does not exist? if !bwa.HasWriter() { bwa.logger.Debug("Rotate true: ", "no writer") return true, nil } // File can be accessed? if !bwa.GetWriter().IsAccessible() { bwa.logger.Debug("Rotate false: ", "no access") return false, errors.New("can' access file to rotate") } // File needs rotation? if !rotate.Enabled { bwa.logger.Debug("Rotate false: ", "not active") return false, nil } if forceRotate { bwa.logger.Debug("Rotate true: ", "forced") return true, nil } // File is too large? if bwa.GetWriter().Size() >= rotate.SizeByte { bwa.logger.Debug("Rotate true: ", "size > rotation size") return true, nil // ### return, too large ### } // File is too old? if time.Since(bwa.Created) >= rotate.Timeout { bwa.logger.Debug("Rotate true: ", "lifetime > timeout setting") return true, nil // ### return, too old ### } // RotateAt crossed? if rotate.AtHour > -1 && rotate.AtMinute > -1 { now := time.Now() rotateAt := time.Date(now.Year(), now.Month(), now.Day(), rotate.AtHour, rotate.AtMinute, 0, 0, now.Location()) if rotateAt.Before(bwa.Created) { return false, nil } if now.After(rotateAt) { bwa.logger.Debug("Rotate true: ", "rotateAt time reached") return true, nil // ### return, too old ### } } // nope, everything is ok return false, nil }
[ "func", "(", "bwa", "*", "BatchedWriterAssembly", ")", "NeedsRotate", "(", "rotate", "RotateConfig", ",", "forceRotate", "bool", ")", "(", "bool", ",", "error", ")", "{", "// File does not exist?", "if", "!", "bwa", ".", "HasWriter", "(", ")", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "\n", "}", "\n\n", "// File can be accessed?", "if", "!", "bwa", ".", "GetWriter", "(", ")", ".", "IsAccessible", "(", ")", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// File needs rotation?", "if", "!", "rotate", ".", "Enabled", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "false", ",", "nil", "\n", "}", "\n\n", "if", "forceRotate", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "\n", "}", "\n\n", "// File is too large?", "if", "bwa", ".", "GetWriter", "(", ")", ".", "Size", "(", ")", ">=", "rotate", ".", "SizeByte", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "// ### return, too large ###", "\n", "}", "\n\n", "// File is too old?", "if", "time", ".", "Since", "(", "bwa", ".", "Created", ")", ">=", "rotate", ".", "Timeout", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "// ### return, too old ###", "\n", "}", "\n\n", "// RotateAt crossed?", "if", "rotate", ".", "AtHour", ">", "-", "1", "&&", "rotate", ".", "AtMinute", ">", "-", "1", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "rotateAt", ":=", "time", ".", "Date", "(", "now", ".", "Year", "(", ")", ",", "now", ".", "Month", "(", ")", ",", "now", ".", "Day", "(", ")", ",", "rotate", ".", "AtHour", ",", "rotate", ".", "AtMinute", ",", "0", ",", "0", ",", "now", ".", "Location", "(", ")", ")", "\n\n", "if", "rotateAt", ".", "Before", "(", "bwa", ".", "Created", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "if", "now", ".", "After", "(", "rotateAt", ")", "{", "bwa", ".", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "true", ",", "nil", "// ### return, too old ###", "\n", "}", "\n", "}", "\n\n", "// nope, everything is ok", "return", "false", ",", "nil", "\n", "}" ]
// NeedsRotate evaluate if the BatchedWriterAssembly need to rotate by the FileRotateConfig
[ "NeedsRotate", "evaluate", "if", "the", "BatchedWriterAssembly", "need", "to", "rotate", "by", "the", "FileRotateConfig" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/batchedWriterAssembly.go#L146-L199
train
trivago/gollum
producer/file/pruner.go
Configure
func (pruner *Pruner) Configure(conf core.PluginConfigReader) { if pruner.pruneSize > 0 && pruner.rotate.SizeByte > 0 { pruner.pruneSize -= pruner.rotate.SizeByte >> 20 if pruner.pruneSize <= 0 { pruner.pruneCount = 1 pruner.pruneSize = 0 } } }
go
func (pruner *Pruner) Configure(conf core.PluginConfigReader) { if pruner.pruneSize > 0 && pruner.rotate.SizeByte > 0 { pruner.pruneSize -= pruner.rotate.SizeByte >> 20 if pruner.pruneSize <= 0 { pruner.pruneCount = 1 pruner.pruneSize = 0 } } }
[ "func", "(", "pruner", "*", "Pruner", ")", "Configure", "(", "conf", "core", ".", "PluginConfigReader", ")", "{", "if", "pruner", ".", "pruneSize", ">", "0", "&&", "pruner", ".", "rotate", ".", "SizeByte", ">", "0", "{", "pruner", ".", "pruneSize", "-=", "pruner", ".", "rotate", ".", "SizeByte", ">>", "20", "\n", "if", "pruner", ".", "pruneSize", "<=", "0", "{", "pruner", ".", "pruneCount", "=", "1", "\n", "pruner", ".", "pruneSize", "=", "0", "\n", "}", "\n", "}", "\n", "}" ]
// Configure initializes this object with values from a plugin config.
[ "Configure", "initializes", "this", "object", "with", "values", "from", "a", "plugin", "config", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/pruner.go#L55-L63
train
trivago/gollum
producer/file/pruner.go
Prune
func (pruner *Pruner) Prune(baseFilePath string) { if pruner.pruneHours > 0 { pruner.pruneByHour(baseFilePath, pruner.pruneHours) } if pruner.pruneCount > 0 { pruner.pruneByCount(baseFilePath, pruner.pruneCount) } if pruner.pruneSize > 0 { pruner.pruneToSize(baseFilePath, pruner.pruneSize) } }
go
func (pruner *Pruner) Prune(baseFilePath string) { if pruner.pruneHours > 0 { pruner.pruneByHour(baseFilePath, pruner.pruneHours) } if pruner.pruneCount > 0 { pruner.pruneByCount(baseFilePath, pruner.pruneCount) } if pruner.pruneSize > 0 { pruner.pruneToSize(baseFilePath, pruner.pruneSize) } }
[ "func", "(", "pruner", "*", "Pruner", ")", "Prune", "(", "baseFilePath", "string", ")", "{", "if", "pruner", ".", "pruneHours", ">", "0", "{", "pruner", ".", "pruneByHour", "(", "baseFilePath", ",", "pruner", ".", "pruneHours", ")", "\n", "}", "\n", "if", "pruner", ".", "pruneCount", ">", "0", "{", "pruner", ".", "pruneByCount", "(", "baseFilePath", ",", "pruner", ".", "pruneCount", ")", "\n", "}", "\n", "if", "pruner", ".", "pruneSize", ">", "0", "{", "pruner", ".", "pruneToSize", "(", "baseFilePath", ",", "pruner", ".", "pruneSize", ")", "\n", "}", "\n", "}" ]
// Prune starts prune methods by hours, by count and by size
[ "Prune", "starts", "prune", "methods", "by", "hours", "by", "count", "and", "by", "size" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/pruner.go#L66-L76
train
trivago/gollum
contrib/native/kafka/librdkafka/message.go
UnmarshalBuffer
func UnmarshalBuffer(bufferPtr *C.buffer_t) []byte { length := int(bufferPtr.len) buffer := make([]byte, length) copy(buffer, (*[1 << 30]byte)(bufferPtr.data)[:length:length]) return buffer }
go
func UnmarshalBuffer(bufferPtr *C.buffer_t) []byte { length := int(bufferPtr.len) buffer := make([]byte, length) copy(buffer, (*[1 << 30]byte)(bufferPtr.data)[:length:length]) return buffer }
[ "func", "UnmarshalBuffer", "(", "bufferPtr", "*", "C", ".", "buffer_t", ")", "[", "]", "byte", "{", "length", ":=", "int", "(", "bufferPtr", ".", "len", ")", "\n", "buffer", ":=", "make", "(", "[", "]", "byte", ",", "length", ")", "\n", "copy", "(", "buffer", ",", "(", "*", "[", "1", "<<", "30", "]", "byte", ")", "(", "bufferPtr", ".", "data", ")", "[", ":", "length", ":", "length", "]", ")", "\n", "return", "buffer", "\n", "}" ]
// UnmarshalBuffer creates a byte slice copy from a buffer_t handle.
[ "UnmarshalBuffer", "creates", "a", "byte", "slice", "copy", "from", "a", "buffer_t", "handle", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/librdkafka/message.go#L59-L64
train
trivago/gollum
contrib/native/systemd/systemdconsumer.go
Consume
func (cons *SystemdConsumer) Consume(workers *sync.WaitGroup) { cons.AddMainWorker(workers) go cons.read() cons.ControlLoop() }
go
func (cons *SystemdConsumer) Consume(workers *sync.WaitGroup) { cons.AddMainWorker(workers) go cons.read() cons.ControlLoop() }
[ "func", "(", "cons", "*", "SystemdConsumer", ")", "Consume", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "cons", ".", "AddMainWorker", "(", "workers", ")", "\n", "go", "cons", ".", "read", "(", ")", "\n", "cons", ".", "ControlLoop", "(", ")", "\n", "}" ]
// Consume enables systemd forwarding as configured.
[ "Consume", "enables", "systemd", "forwarding", "as", "configured", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/systemd/systemdconsumer.go#L182-L186
train
trivago/gollum
contrib/native/kafka/librdkafka/client.go
Poll
func (cl *Client) Poll(timeout time.Duration) { if timeout < 0 { C.rd_kafka_poll(cl.handle, -1) } else { timeoutMs := C.int(timeout.Nanoseconds() / 1000000) C.rd_kafka_poll(cl.handle, timeoutMs) } }
go
func (cl *Client) Poll(timeout time.Duration) { if timeout < 0 { C.rd_kafka_poll(cl.handle, -1) } else { timeoutMs := C.int(timeout.Nanoseconds() / 1000000) C.rd_kafka_poll(cl.handle, timeoutMs) } }
[ "func", "(", "cl", "*", "Client", ")", "Poll", "(", "timeout", "time", ".", "Duration", ")", "{", "if", "timeout", "<", "0", "{", "C", ".", "rd_kafka_poll", "(", "cl", ".", "handle", ",", "-", "1", ")", "\n", "}", "else", "{", "timeoutMs", ":=", "C", ".", "int", "(", "timeout", ".", "Nanoseconds", "(", ")", "/", "1000000", ")", "\n", "C", ".", "rd_kafka_poll", "(", "cl", ".", "handle", ",", "timeoutMs", ")", "\n", "}", "\n", "}" ]
// Poll polls for new data to be sent to the async handler functions
[ "Poll", "polls", "for", "new", "data", "to", "be", "sent", "to", "the", "async", "handler", "functions" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/librdkafka/client.go#L63-L70
train
trivago/gollum
contrib/deprecated/producer/s3.go
Produce
func (prod *S3) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) sess, err := session.NewSessionWithOptions(session.Options{ Config: *prod.config, SharedConfigState: session.SharedConfigEnable, }) if err != nil { prod.Logger.WithError(err).Error("Failed to create session") } if prod.assumeRole != "" { creds := stscreds.NewCredentials(sess, prod.assumeRole) prod.client = s3.New(sess, &aws.Config{Credentials: creds}) } else { prod.client = s3.New(sess) } prod.TickerMessageControlLoop(prod.bufferMessage, prod.flushFrequency, prod.sendBatchOnTimeOut) }
go
func (prod *S3) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) sess, err := session.NewSessionWithOptions(session.Options{ Config: *prod.config, SharedConfigState: session.SharedConfigEnable, }) if err != nil { prod.Logger.WithError(err).Error("Failed to create session") } if prod.assumeRole != "" { creds := stscreds.NewCredentials(sess, prod.assumeRole) prod.client = s3.New(sess, &aws.Config{Credentials: creds}) } else { prod.client = s3.New(sess) } prod.TickerMessageControlLoop(prod.bufferMessage, prod.flushFrequency, prod.sendBatchOnTimeOut) }
[ "func", "(", "prod", "*", "S3", ")", "Produce", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "prod", ".", "AddMainWorker", "(", "workers", ")", "\n", "sess", ",", "err", ":=", "session", ".", "NewSessionWithOptions", "(", "session", ".", "Options", "{", "Config", ":", "*", "prod", ".", "config", ",", "SharedConfigState", ":", "session", ".", "SharedConfigEnable", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "prod", ".", "Logger", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "prod", ".", "assumeRole", "!=", "\"", "\"", "{", "creds", ":=", "stscreds", ".", "NewCredentials", "(", "sess", ",", "prod", ".", "assumeRole", ")", "\n", "prod", ".", "client", "=", "s3", ".", "New", "(", "sess", ",", "&", "aws", ".", "Config", "{", "Credentials", ":", "creds", "}", ")", "\n", "}", "else", "{", "prod", ".", "client", "=", "s3", ".", "New", "(", "sess", ")", "\n", "}", "\n\n", "prod", ".", "TickerMessageControlLoop", "(", "prod", ".", "bufferMessage", ",", "prod", ".", "flushFrequency", ",", "prod", ".", "sendBatchOnTimeOut", ")", "\n", "}" ]
// Produce writes to a buffer that is sent to amazon s3.
[ "Produce", "writes", "to", "a", "buffer", "that", "is", "sent", "to", "amazon", "s3", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/deprecated/producer/s3.go#L587-L605
train
trivago/gollum
core/message.go
NewMessage
func NewMessage(source MessageSource, data []byte, metadata Metadata, streamID MessageStreamID) *Message { msg := &Message{ source: source, streamID: streamID, origStreamID: streamID, timestamp: time.Now().UnixNano(), } msg.data.payload = getPayloadCopy(data) if metadata != nil && len(metadata) > 0 { msg.data.metadata = metadata } return msg }
go
func NewMessage(source MessageSource, data []byte, metadata Metadata, streamID MessageStreamID) *Message { msg := &Message{ source: source, streamID: streamID, origStreamID: streamID, timestamp: time.Now().UnixNano(), } msg.data.payload = getPayloadCopy(data) if metadata != nil && len(metadata) > 0 { msg.data.metadata = metadata } return msg }
[ "func", "NewMessage", "(", "source", "MessageSource", ",", "data", "[", "]", "byte", ",", "metadata", "Metadata", ",", "streamID", "MessageStreamID", ")", "*", "Message", "{", "msg", ":=", "&", "Message", "{", "source", ":", "source", ",", "streamID", ":", "streamID", ",", "origStreamID", ":", "streamID", ",", "timestamp", ":", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ",", "}", "\n\n", "msg", ".", "data", ".", "payload", "=", "getPayloadCopy", "(", "data", ")", "\n", "if", "metadata", "!=", "nil", "&&", "len", "(", "metadata", ")", ">", "0", "{", "msg", ".", "data", ".", "metadata", "=", "metadata", "\n", "}", "\n\n", "return", "msg", "\n", "}" ]
// NewMessage creates a new message from a given data stream by copying data.
[ "NewMessage", "creates", "a", "new", "message", "from", "a", "given", "data", "stream", "by", "copying", "data", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L43-L57
train
trivago/gollum
core/message.go
getPayloadCopy
func getPayloadCopy(data []byte) (buffer []byte) { buffer = make([]byte, len(data)) copy(buffer, data) return }
go
func getPayloadCopy(data []byte) (buffer []byte) { buffer = make([]byte, len(data)) copy(buffer, data) return }
[ "func", "getPayloadCopy", "(", "data", "[", "]", "byte", ")", "(", "buffer", "[", "]", "byte", ")", "{", "buffer", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "data", ")", ")", "\n", "copy", "(", "buffer", ",", "data", ")", "\n", "return", "\n", "}" ]
// getPayloadCopy return a copy of the data byte array
[ "getPayloadCopy", "return", "a", "copy", "of", "the", "data", "byte", "array" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L60-L64
train
trivago/gollum
core/message.go
SetStreamID
func (msg *Message) SetStreamID(streamID MessageStreamID) { msg.prevStreamID = msg.streamID msg.streamID = streamID }
go
func (msg *Message) SetStreamID(streamID MessageStreamID) { msg.prevStreamID = msg.streamID msg.streamID = streamID }
[ "func", "(", "msg", "*", "Message", ")", "SetStreamID", "(", "streamID", "MessageStreamID", ")", "{", "msg", ".", "prevStreamID", "=", "msg", ".", "streamID", "\n", "msg", ".", "streamID", "=", "streamID", "\n", "}" ]
// SetStreamID sets a new stream and stores the current one in the previous // stream field. This method does not affect the original stream ID.
[ "SetStreamID", "sets", "a", "new", "stream", "and", "stores", "the", "current", "one", "in", "the", "previous", "stream", "field", ".", "This", "method", "does", "not", "affect", "the", "original", "stream", "ID", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L103-L106
train
trivago/gollum
core/message.go
GetMetadata
func (msg *Message) GetMetadata() Metadata { if msg.data.metadata == nil { msg.data.metadata = make(Metadata) } return msg.data.metadata }
go
func (msg *Message) GetMetadata() Metadata { if msg.data.metadata == nil { msg.data.metadata = make(Metadata) } return msg.data.metadata }
[ "func", "(", "msg", "*", "Message", ")", "GetMetadata", "(", ")", "Metadata", "{", "if", "msg", ".", "data", ".", "metadata", "==", "nil", "{", "msg", ".", "data", ".", "metadata", "=", "make", "(", "Metadata", ")", "\n", "}", "\n", "return", "msg", ".", "data", ".", "metadata", "\n", "}" ]
// GetMetadata returns the current Metadata. If no metadata is present, the // metadata map will be created by this call.
[ "GetMetadata", "returns", "the", "current", "Metadata", ".", "If", "no", "metadata", "is", "present", "the", "metadata", "map", "will", "be", "created", "by", "this", "call", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L133-L138
train
trivago/gollum
core/message.go
StorePayload
func (msg *Message) StorePayload(data []byte) { if len(data) <= cap(msg.data.payload) { msg.data.payload = msg.data.payload[:len(data)] copy(msg.data.payload, data) } else { msg.data.payload = data } }
go
func (msg *Message) StorePayload(data []byte) { if len(data) <= cap(msg.data.payload) { msg.data.payload = msg.data.payload[:len(data)] copy(msg.data.payload, data) } else { msg.data.payload = data } }
[ "func", "(", "msg", "*", "Message", ")", "StorePayload", "(", "data", "[", "]", "byte", ")", "{", "if", "len", "(", "data", ")", "<=", "cap", "(", "msg", ".", "data", ".", "payload", ")", "{", "msg", ".", "data", ".", "payload", "=", "msg", ".", "data", ".", "payload", "[", ":", "len", "(", "data", ")", "]", "\n", "copy", "(", "msg", ".", "data", ".", "payload", ",", "data", ")", "\n", "}", "else", "{", "msg", ".", "data", ".", "payload", "=", "data", "\n", "}", "\n", "}" ]
// StorePayload copies data into the hold data buffer. If the buffer can hold // data it is resized, otherwise a new buffer will be allocated.
[ "StorePayload", "copies", "data", "into", "the", "hold", "data", "buffer", ".", "If", "the", "buffer", "can", "hold", "data", "it", "is", "resized", "otherwise", "a", "new", "buffer", "will", "be", "allocated", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L148-L155
train
trivago/gollum
core/message.go
Clone
func (msg *Message) Clone() *Message { clone := *msg clone.data.payload = make([]byte, len(msg.data.payload)) copy(clone.data.payload, msg.data.payload) return &clone }
go
func (msg *Message) Clone() *Message { clone := *msg clone.data.payload = make([]byte, len(msg.data.payload)) copy(clone.data.payload, msg.data.payload) return &clone }
[ "func", "(", "msg", "*", "Message", ")", "Clone", "(", ")", "*", "Message", "{", "clone", ":=", "*", "msg", "\n\n", "clone", ".", "data", ".", "payload", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "msg", ".", "data", ".", "payload", ")", ")", "\n", "copy", "(", "clone", ".", "data", ".", "payload", ",", "msg", ".", "data", ".", "payload", ")", "\n\n", "return", "&", "clone", "\n", "}" ]
// Clone returns a copy of this message, i.e. the payload is duplicated. // The created timestamp is copied, too.
[ "Clone", "returns", "a", "copy", "of", "this", "message", "i", ".", "e", ".", "the", "payload", "is", "duplicated", ".", "The", "created", "timestamp", "is", "copied", "too", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L159-L166
train
trivago/gollum
core/message.go
CloneOriginal
func (msg *Message) CloneOriginal() *Message { if msg.orig == nil { msg.FreezeOriginal() } clone := *msg clone.data.payload = make([]byte, len(msg.orig.payload)) copy(clone.data.payload, msg.orig.payload) if msg.orig.metadata != nil { clone.data.metadata = msg.orig.metadata.Clone() } else { clone.data.metadata = nil } clone.SetStreamID(msg.origStreamID) return &clone }
go
func (msg *Message) CloneOriginal() *Message { if msg.orig == nil { msg.FreezeOriginal() } clone := *msg clone.data.payload = make([]byte, len(msg.orig.payload)) copy(clone.data.payload, msg.orig.payload) if msg.orig.metadata != nil { clone.data.metadata = msg.orig.metadata.Clone() } else { clone.data.metadata = nil } clone.SetStreamID(msg.origStreamID) return &clone }
[ "func", "(", "msg", "*", "Message", ")", "CloneOriginal", "(", ")", "*", "Message", "{", "if", "msg", ".", "orig", "==", "nil", "{", "msg", ".", "FreezeOriginal", "(", ")", "\n", "}", "\n\n", "clone", ":=", "*", "msg", "\n", "clone", ".", "data", ".", "payload", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "msg", ".", "orig", ".", "payload", ")", ")", "\n", "copy", "(", "clone", ".", "data", ".", "payload", ",", "msg", ".", "orig", ".", "payload", ")", "\n\n", "if", "msg", ".", "orig", ".", "metadata", "!=", "nil", "{", "clone", ".", "data", ".", "metadata", "=", "msg", ".", "orig", ".", "metadata", ".", "Clone", "(", ")", "\n", "}", "else", "{", "clone", ".", "data", ".", "metadata", "=", "nil", "\n", "}", "\n\n", "clone", ".", "SetStreamID", "(", "msg", ".", "origStreamID", ")", "\n", "return", "&", "clone", "\n", "}" ]
// CloneOriginal returns a copy of this message with the original payload and // stream. If FreezeOriginal has not been called before it will be at this point // so that all subsequential calls will use the same original.
[ "CloneOriginal", "returns", "a", "copy", "of", "this", "message", "with", "the", "original", "payload", "and", "stream", ".", "If", "FreezeOriginal", "has", "not", "been", "called", "before", "it", "will", "be", "at", "this", "point", "so", "that", "all", "subsequential", "calls", "will", "use", "the", "same", "original", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L171-L188
train
trivago/gollum
core/message.go
FreezeOriginal
func (msg *Message) FreezeOriginal() { // Freeze may be called only once if msg.orig != nil { return } var metadata Metadata if msg.data.metadata != nil { metadata = msg.data.metadata.Clone() } msg.orig = &MessageData{ payload: getPayloadCopy(msg.data.payload), metadata: metadata, } }
go
func (msg *Message) FreezeOriginal() { // Freeze may be called only once if msg.orig != nil { return } var metadata Metadata if msg.data.metadata != nil { metadata = msg.data.metadata.Clone() } msg.orig = &MessageData{ payload: getPayloadCopy(msg.data.payload), metadata: metadata, } }
[ "func", "(", "msg", "*", "Message", ")", "FreezeOriginal", "(", ")", "{", "// Freeze may be called only once", "if", "msg", ".", "orig", "!=", "nil", "{", "return", "\n", "}", "\n\n", "var", "metadata", "Metadata", "\n", "if", "msg", ".", "data", ".", "metadata", "!=", "nil", "{", "metadata", "=", "msg", ".", "data", ".", "metadata", ".", "Clone", "(", ")", "\n", "}", "\n\n", "msg", ".", "orig", "=", "&", "MessageData", "{", "payload", ":", "getPayloadCopy", "(", "msg", ".", "data", ".", "payload", ")", ",", "metadata", ":", "metadata", ",", "}", "\n", "}" ]
// FreezeOriginal will take the current state of the message and store it as // the "original" message. This function can only be called once for each // message. Please note that this function only affects payload and metadata and // can only be called once. Additional calls will have no effect. // The original stream ID can be changed at any time by using SetOrigStreamID.
[ "FreezeOriginal", "will", "take", "the", "current", "state", "of", "the", "message", "and", "store", "it", "as", "the", "original", "message", ".", "This", "function", "can", "only", "be", "called", "once", "for", "each", "message", ".", "Please", "note", "that", "this", "function", "only", "affects", "payload", "and", "metadata", "and", "can", "only", "be", "called", "once", ".", "Additional", "calls", "will", "have", "no", "effect", ".", "The", "original", "stream", "ID", "can", "be", "changed", "at", "any", "time", "by", "using", "SetOrigStreamID", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L195-L210
train
trivago/gollum
core/message.go
DeserializeMessage
func DeserializeMessage(data []byte) (*Message, error) { serializable := new(SerializedMessage) if err := proto.Unmarshal(data, serializable); err != nil { return nil, err } msg := &Message{ streamID: MessageStreamID(serializable.GetStreamID()), prevStreamID: MessageStreamID(serializable.GetPrevStreamID()), origStreamID: MessageStreamID(serializable.GetOrigStreamID()), timestamp: serializable.GetTimestamp(), } if msgData := serializable.GetData(); msgData != nil { msg.data.payload = msgData.GetData() msg.data.metadata = msgData.GetMetadata() } if msgOrigData := serializable.GetOriginal(); msgOrigData != nil { msg.orig = new(MessageData) msg.orig.payload = msgOrigData.GetData() msg.orig.metadata = msgOrigData.GetMetadata() } return msg, nil }
go
func DeserializeMessage(data []byte) (*Message, error) { serializable := new(SerializedMessage) if err := proto.Unmarshal(data, serializable); err != nil { return nil, err } msg := &Message{ streamID: MessageStreamID(serializable.GetStreamID()), prevStreamID: MessageStreamID(serializable.GetPrevStreamID()), origStreamID: MessageStreamID(serializable.GetOrigStreamID()), timestamp: serializable.GetTimestamp(), } if msgData := serializable.GetData(); msgData != nil { msg.data.payload = msgData.GetData() msg.data.metadata = msgData.GetMetadata() } if msgOrigData := serializable.GetOriginal(); msgOrigData != nil { msg.orig = new(MessageData) msg.orig.payload = msgOrigData.GetData() msg.orig.metadata = msgOrigData.GetMetadata() } return msg, nil }
[ "func", "DeserializeMessage", "(", "data", "[", "]", "byte", ")", "(", "*", "Message", ",", "error", ")", "{", "serializable", ":=", "new", "(", "SerializedMessage", ")", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "data", ",", "serializable", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "msg", ":=", "&", "Message", "{", "streamID", ":", "MessageStreamID", "(", "serializable", ".", "GetStreamID", "(", ")", ")", ",", "prevStreamID", ":", "MessageStreamID", "(", "serializable", ".", "GetPrevStreamID", "(", ")", ")", ",", "origStreamID", ":", "MessageStreamID", "(", "serializable", ".", "GetOrigStreamID", "(", ")", ")", ",", "timestamp", ":", "serializable", ".", "GetTimestamp", "(", ")", ",", "}", "\n\n", "if", "msgData", ":=", "serializable", ".", "GetData", "(", ")", ";", "msgData", "!=", "nil", "{", "msg", ".", "data", ".", "payload", "=", "msgData", ".", "GetData", "(", ")", "\n", "msg", ".", "data", ".", "metadata", "=", "msgData", ".", "GetMetadata", "(", ")", "\n", "}", "\n\n", "if", "msgOrigData", ":=", "serializable", ".", "GetOriginal", "(", ")", ";", "msgOrigData", "!=", "nil", "{", "msg", ".", "orig", "=", "new", "(", "MessageData", ")", "\n", "msg", ".", "orig", ".", "payload", "=", "msgOrigData", ".", "GetData", "(", ")", "\n", "msg", ".", "orig", ".", "metadata", "=", "msgOrigData", ".", "GetMetadata", "(", ")", "\n", "}", "\n\n", "return", "msg", ",", "nil", "\n", "}" ]
// DeserializeMessage generates a message from a byte array produced by // Message.Serialize. Please note that the payload is restored but the original // data is not. As of this FreezeOriginal can be called again after this call.
[ "DeserializeMessage", "generates", "a", "message", "from", "a", "byte", "array", "produced", "by", "Message", ".", "Serialize", ".", "Please", "note", "that", "the", "payload", "is", "restored", "but", "the", "original", "data", "is", "not", ".", "As", "of", "this", "FreezeOriginal", "can", "be", "called", "again", "after", "this", "call", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/message.go#L241-L266
train
trivago/gollum
producer/spooling.go
TryFallback
func (prod *Spooling) TryFallback(msg *core.Message) { if prod.revertOnDrop { msg.SetStreamID(msg.GetPrevStreamID()) } prod.BufferedProducer.TryFallback(msg) }
go
func (prod *Spooling) TryFallback(msg *core.Message) { if prod.revertOnDrop { msg.SetStreamID(msg.GetPrevStreamID()) } prod.BufferedProducer.TryFallback(msg) }
[ "func", "(", "prod", "*", "Spooling", ")", "TryFallback", "(", "msg", "*", "core", ".", "Message", ")", "{", "if", "prod", ".", "revertOnDrop", "{", "msg", ".", "SetStreamID", "(", "msg", ".", "GetPrevStreamID", "(", ")", ")", "\n", "}", "\n", "prod", ".", "BufferedProducer", ".", "TryFallback", "(", "msg", ")", "\n", "}" ]
// TryFallback reverts the message stream before dropping
[ "TryFallback", "reverts", "the", "message", "stream", "before", "dropping" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/spooling.go#L142-L147
train
trivago/gollum
producer/spooling.go
openExistingFiles
func (prod *Spooling) openExistingFiles() { prod.Logger.Debug("Looking for spool files to read") files, _ := ioutil.ReadDir(prod.path) for _, file := range files { if file.IsDir() { streamName := filepath.Base(file.Name()) streamID := core.StreamRegistry.GetStreamID(streamName) // Only create a new spooler if the stream is registered by this instance prod.outfileGuard.Lock() if _, exists := prod.outfile[streamID]; !exists && core.StreamRegistry.IsStreamRegistered(streamID) { prod.Logger.Infof("Found existing spooling folders for %s", streamName) prod.outfile[streamID] = newSpoolFile(prod, streamName, nil) } prod.outfileGuard.Unlock() } } // Keep looking for new streams if prod.IsActive() { prod.spoolCheck = time.AfterFunc(prod.respoolDuration, prod.openExistingFiles) } }
go
func (prod *Spooling) openExistingFiles() { prod.Logger.Debug("Looking for spool files to read") files, _ := ioutil.ReadDir(prod.path) for _, file := range files { if file.IsDir() { streamName := filepath.Base(file.Name()) streamID := core.StreamRegistry.GetStreamID(streamName) // Only create a new spooler if the stream is registered by this instance prod.outfileGuard.Lock() if _, exists := prod.outfile[streamID]; !exists && core.StreamRegistry.IsStreamRegistered(streamID) { prod.Logger.Infof("Found existing spooling folders for %s", streamName) prod.outfile[streamID] = newSpoolFile(prod, streamName, nil) } prod.outfileGuard.Unlock() } } // Keep looking for new streams if prod.IsActive() { prod.spoolCheck = time.AfterFunc(prod.respoolDuration, prod.openExistingFiles) } }
[ "func", "(", "prod", "*", "Spooling", ")", "openExistingFiles", "(", ")", "{", "prod", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "files", ",", "_", ":=", "ioutil", ".", "ReadDir", "(", "prod", ".", "path", ")", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "if", "file", ".", "IsDir", "(", ")", "{", "streamName", ":=", "filepath", ".", "Base", "(", "file", ".", "Name", "(", ")", ")", "\n", "streamID", ":=", "core", ".", "StreamRegistry", ".", "GetStreamID", "(", "streamName", ")", "\n\n", "// Only create a new spooler if the stream is registered by this instance", "prod", ".", "outfileGuard", ".", "Lock", "(", ")", "\n", "if", "_", ",", "exists", ":=", "prod", ".", "outfile", "[", "streamID", "]", ";", "!", "exists", "&&", "core", ".", "StreamRegistry", ".", "IsStreamRegistered", "(", "streamID", ")", "{", "prod", ".", "Logger", ".", "Infof", "(", "\"", "\"", ",", "streamName", ")", "\n", "prod", ".", "outfile", "[", "streamID", "]", "=", "newSpoolFile", "(", "prod", ",", "streamName", ",", "nil", ")", "\n", "}", "\n", "prod", ".", "outfileGuard", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n\n", "// Keep looking for new streams", "if", "prod", ".", "IsActive", "(", ")", "{", "prod", ".", "spoolCheck", "=", "time", ".", "AfterFunc", "(", "prod", ".", "respoolDuration", ",", "prod", ".", "openExistingFiles", ")", "\n", "}", "\n", "}" ]
// As we might share spooling folders with different instances we only read // streams that we actually care about.
[ "As", "we", "might", "share", "spooling", "folders", "with", "different", "instances", "we", "only", "read", "streams", "that", "we", "actually", "care", "about", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/spooling.go#L288-L310
train
trivago/gollum
core/bufferedproducer.go
DefaultDrain
func (prod *BufferedProducer) DefaultDrain() { if prod.onMessage != nil { prod.DrainMessageChannel(prod.onMessage, prod.shutdownTimeout) } }
go
func (prod *BufferedProducer) DefaultDrain() { if prod.onMessage != nil { prod.DrainMessageChannel(prod.onMessage, prod.shutdownTimeout) } }
[ "func", "(", "prod", "*", "BufferedProducer", ")", "DefaultDrain", "(", ")", "{", "if", "prod", ".", "onMessage", "!=", "nil", "{", "prod", ".", "DrainMessageChannel", "(", "prod", ".", "onMessage", ",", "prod", ".", "shutdownTimeout", ")", "\n", "}", "\n", "}" ]
// DefaultDrain is the function registered to onPrepareStop by default. // It calls DrainMessageChannel with the message handling function passed to // Any of the control functions. If no such call happens, this function does // nothing.
[ "DefaultDrain", "is", "the", "function", "registered", "to", "onPrepareStop", "by", "default", ".", "It", "calls", "DrainMessageChannel", "with", "the", "message", "handling", "function", "passed", "to", "Any", "of", "the", "control", "functions", ".", "If", "no", "such", "call", "happens", "this", "function", "does", "nothing", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/bufferedproducer.go#L101-L105
train
trivago/gollum
core/bufferedproducer.go
DrainMessageChannel
func (prod *BufferedProducer) DrainMessageChannel(handleMessage func(*Message), timeout time.Duration) bool { for { if msg, ok := prod.messages.PopWithTimeout(timeout); ok { if !tgo.ReturnAfter(prod.shutdownTimeout, func() { handleMessage(msg) }) { return false // ### return, done ### } } else { return prod.messages.IsEmpty() // ### return, done ### } } }
go
func (prod *BufferedProducer) DrainMessageChannel(handleMessage func(*Message), timeout time.Duration) bool { for { if msg, ok := prod.messages.PopWithTimeout(timeout); ok { if !tgo.ReturnAfter(prod.shutdownTimeout, func() { handleMessage(msg) }) { return false // ### return, done ### } } else { return prod.messages.IsEmpty() // ### return, done ### } } }
[ "func", "(", "prod", "*", "BufferedProducer", ")", "DrainMessageChannel", "(", "handleMessage", "func", "(", "*", "Message", ")", ",", "timeout", "time", ".", "Duration", ")", "bool", "{", "for", "{", "if", "msg", ",", "ok", ":=", "prod", ".", "messages", ".", "PopWithTimeout", "(", "timeout", ")", ";", "ok", "{", "if", "!", "tgo", ".", "ReturnAfter", "(", "prod", ".", "shutdownTimeout", ",", "func", "(", ")", "{", "handleMessage", "(", "msg", ")", "}", ")", "{", "return", "false", "// ### return, done ###", "\n", "}", "\n", "}", "else", "{", "return", "prod", ".", "messages", ".", "IsEmpty", "(", ")", "// ### return, done ###", "\n", "}", "\n", "}", "\n", "}" ]
// DrainMessageChannel empties the message channel. This functions returns // after the queue being empty for a given amount of time or when the queue // has been closed and no more messages are available. The return value // indicates wether the channel is empty or not.
[ "DrainMessageChannel", "empties", "the", "message", "channel", ".", "This", "functions", "returns", "after", "the", "queue", "being", "empty", "for", "a", "given", "amount", "of", "time", "or", "when", "the", "queue", "has", "been", "closed", "and", "no", "more", "messages", "are", "available", ".", "The", "return", "value", "indicates", "wether", "the", "channel", "is", "empty", "or", "not", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/bufferedproducer.go#L111-L121
train
trivago/gollum
core/bufferedproducer.go
DefaultClose
func (prod *BufferedProducer) DefaultClose() { if prod.onMessage != nil { prod.CloseMessageChannel(prod.onMessage) } }
go
func (prod *BufferedProducer) DefaultClose() { if prod.onMessage != nil { prod.CloseMessageChannel(prod.onMessage) } }
[ "func", "(", "prod", "*", "BufferedProducer", ")", "DefaultClose", "(", ")", "{", "if", "prod", ".", "onMessage", "!=", "nil", "{", "prod", ".", "CloseMessageChannel", "(", "prod", ".", "onMessage", ")", "\n", "}", "\n", "}" ]
// DefaultClose is the function registered to onStop by default. // It calls CloseMessageChannel with the message handling function passed to // Any of the control functions. If no such call happens, this function does // nothing.
[ "DefaultClose", "is", "the", "function", "registered", "to", "onStop", "by", "default", ".", "It", "calls", "CloseMessageChannel", "with", "the", "message", "handling", "function", "passed", "to", "Any", "of", "the", "control", "functions", ".", "If", "no", "such", "call", "happens", "this", "function", "does", "nothing", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/bufferedproducer.go#L127-L131
train
trivago/gollum
core/bufferedproducer.go
CloseMessageChannel
func (prod *BufferedProducer) CloseMessageChannel(handleMessage func(*Message)) (empty bool) { prod.DrainMessageChannel(handleMessage, prod.shutdownTimeout) prod.messages.Close() defer func() { if !prod.messages.IsEmpty() { prod.Logger.Errorf("%d messages left after closing.", prod.messages.GetNumQueued()) } }() for { if msg, ok := prod.messages.Pop(); ok { if !tgo.ReturnAfter(prod.shutdownTimeout, func() { handleMessage(msg) }) { return false // ### return, failed to handle message ### } } else { return true // ### return, done ### } } }
go
func (prod *BufferedProducer) CloseMessageChannel(handleMessage func(*Message)) (empty bool) { prod.DrainMessageChannel(handleMessage, prod.shutdownTimeout) prod.messages.Close() defer func() { if !prod.messages.IsEmpty() { prod.Logger.Errorf("%d messages left after closing.", prod.messages.GetNumQueued()) } }() for { if msg, ok := prod.messages.Pop(); ok { if !tgo.ReturnAfter(prod.shutdownTimeout, func() { handleMessage(msg) }) { return false // ### return, failed to handle message ### } } else { return true // ### return, done ### } } }
[ "func", "(", "prod", "*", "BufferedProducer", ")", "CloseMessageChannel", "(", "handleMessage", "func", "(", "*", "Message", ")", ")", "(", "empty", "bool", ")", "{", "prod", ".", "DrainMessageChannel", "(", "handleMessage", ",", "prod", ".", "shutdownTimeout", ")", "\n", "prod", ".", "messages", ".", "Close", "(", ")", "\n\n", "defer", "func", "(", ")", "{", "if", "!", "prod", ".", "messages", ".", "IsEmpty", "(", ")", "{", "prod", ".", "Logger", ".", "Errorf", "(", "\"", "\"", ",", "prod", ".", "messages", ".", "GetNumQueued", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "for", "{", "if", "msg", ",", "ok", ":=", "prod", ".", "messages", ".", "Pop", "(", ")", ";", "ok", "{", "if", "!", "tgo", ".", "ReturnAfter", "(", "prod", ".", "shutdownTimeout", ",", "func", "(", ")", "{", "handleMessage", "(", "msg", ")", "}", ")", "{", "return", "false", "// ### return, failed to handle message ###", "\n", "}", "\n", "}", "else", "{", "return", "true", "// ### return, done ###", "\n", "}", "\n", "}", "\n", "}" ]
// CloseMessageChannel first calls DrainMessageChannel with shutdown timeout, // closes the channel afterwards and calls DrainMessageChannel again to make // sure all messages are actually gone. The return value indicates wether // the channel is empty or not.
[ "CloseMessageChannel", "first", "calls", "DrainMessageChannel", "with", "shutdown", "timeout", "closes", "the", "channel", "afterwards", "and", "calls", "DrainMessageChannel", "again", "to", "make", "sure", "all", "messages", "are", "actually", "gone", ".", "The", "return", "value", "indicates", "wether", "the", "channel", "is", "empty", "or", "not", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/bufferedproducer.go#L137-L156
train
trivago/gollum
core/logconsumer.go
Consume
func (cons *LogConsumer) Consume(threads *sync.WaitGroup) { // Wait for control statements for { select { case msg := <-cons.queue: cons.logRouter.Enqueue(msg) case command := <-cons.control: if command == PluginControlStopConsumer { cons.queue.Close() for msg := range cons.queue { cons.logRouter.Enqueue(msg) } cons.stopped = true return // ### return ### } } } }
go
func (cons *LogConsumer) Consume(threads *sync.WaitGroup) { // Wait for control statements for { select { case msg := <-cons.queue: cons.logRouter.Enqueue(msg) case command := <-cons.control: if command == PluginControlStopConsumer { cons.queue.Close() for msg := range cons.queue { cons.logRouter.Enqueue(msg) } cons.stopped = true return // ### return ### } } } }
[ "func", "(", "cons", "*", "LogConsumer", ")", "Consume", "(", "threads", "*", "sync", ".", "WaitGroup", ")", "{", "// Wait for control statements", "for", "{", "select", "{", "case", "msg", ":=", "<-", "cons", ".", "queue", ":", "cons", ".", "logRouter", ".", "Enqueue", "(", "msg", ")", "\n\n", "case", "command", ":=", "<-", "cons", ".", "control", ":", "if", "command", "==", "PluginControlStopConsumer", "{", "cons", ".", "queue", ".", "Close", "(", ")", "\n", "for", "msg", ":=", "range", "cons", ".", "queue", "{", "cons", ".", "logRouter", ".", "Enqueue", "(", "msg", ")", "\n", "}", "\n", "cons", ".", "stopped", "=", "true", "\n", "return", "// ### return ###", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Consume starts listening for control statements
[ "Consume", "starts", "listening", "for", "control", "statements" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/logconsumer.go#L98-L116
train
trivago/gollum
contrib/native/kafka/kafkaproducer.go
OnMessageDelivered
func (prod *KafkaProducer) OnMessageDelivered(userdata []byte) { if msg, err := core.DeserializeMessage(userdata); err == nil { prod.storeRTT(msg) } else { prod.Logger.Error(err) } }
go
func (prod *KafkaProducer) OnMessageDelivered(userdata []byte) { if msg, err := core.DeserializeMessage(userdata); err == nil { prod.storeRTT(msg) } else { prod.Logger.Error(err) } }
[ "func", "(", "prod", "*", "KafkaProducer", ")", "OnMessageDelivered", "(", "userdata", "[", "]", "byte", ")", "{", "if", "msg", ",", "err", ":=", "core", ".", "DeserializeMessage", "(", "userdata", ")", ";", "err", "==", "nil", "{", "prod", ".", "storeRTT", "(", "msg", ")", "\n", "}", "else", "{", "prod", ".", "Logger", ".", "Error", "(", "err", ")", "\n", "}", "\n", "}" ]
// OnMessageDelivered gets called by librdkafka on message delivery success
[ "OnMessageDelivered", "gets", "called", "by", "librdkafka", "on", "message", "delivery", "success" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/kafkaproducer.go#L383-L389
train
trivago/gollum
contrib/native/kafka/kafkaproducer.go
OnMessageError
func (prod *KafkaProducer) OnMessageError(reason string, userdata []byte) { prod.Logger.Error("Message delivery failed:", reason) if msg, err := core.DeserializeMessage(userdata); err == nil { prod.storeRTT(msg) prod.TryFallback(msg) } else { prod.Logger.Error(err) } }
go
func (prod *KafkaProducer) OnMessageError(reason string, userdata []byte) { prod.Logger.Error("Message delivery failed:", reason) if msg, err := core.DeserializeMessage(userdata); err == nil { prod.storeRTT(msg) prod.TryFallback(msg) } else { prod.Logger.Error(err) } }
[ "func", "(", "prod", "*", "KafkaProducer", ")", "OnMessageError", "(", "reason", "string", ",", "userdata", "[", "]", "byte", ")", "{", "prod", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "reason", ")", "\n", "if", "msg", ",", "err", ":=", "core", ".", "DeserializeMessage", "(", "userdata", ")", ";", "err", "==", "nil", "{", "prod", ".", "storeRTT", "(", "msg", ")", "\n", "prod", ".", "TryFallback", "(", "msg", ")", "\n", "}", "else", "{", "prod", ".", "Logger", ".", "Error", "(", "err", ")", "\n", "}", "\n", "}" ]
// OnMessageError gets called by librdkafka on message delivery failure
[ "OnMessageError", "gets", "called", "by", "librdkafka", "on", "message", "delivery", "failure" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/kafkaproducer.go#L392-L400
train
trivago/gollum
core/pluginconfig.go
NewPluginConfig
func NewPluginConfig(pluginID string, defaultTypename string) PluginConfig { return PluginConfig{ Enable: true, ID: pluginID, Typename: defaultTypename, Settings: tcontainer.NewMarshalMap(), validKeys: make(map[string]bool), } }
go
func NewPluginConfig(pluginID string, defaultTypename string) PluginConfig { return PluginConfig{ Enable: true, ID: pluginID, Typename: defaultTypename, Settings: tcontainer.NewMarshalMap(), validKeys: make(map[string]bool), } }
[ "func", "NewPluginConfig", "(", "pluginID", "string", ",", "defaultTypename", "string", ")", "PluginConfig", "{", "return", "PluginConfig", "{", "Enable", ":", "true", ",", "ID", ":", "pluginID", ",", "Typename", ":", "defaultTypename", ",", "Settings", ":", "tcontainer", ".", "NewMarshalMap", "(", ")", ",", "validKeys", ":", "make", "(", "map", "[", "string", "]", "bool", ")", ",", "}", "\n", "}" ]
// NewPluginConfig creates a new plugin config with default values. // By default the plugin is enabled, has one instance and has no additional settings. // Passing an empty pluginID makes the plugin anonymous. // The defaultTypename may be overridden by a later call to read.
[ "NewPluginConfig", "creates", "a", "new", "plugin", "config", "with", "default", "values", ".", "By", "default", "the", "plugin", "is", "enabled", "has", "one", "instance", "and", "has", "no", "additional", "settings", ".", "Passing", "an", "empty", "pluginID", "makes", "the", "plugin", "anonymous", ".", "The", "defaultTypename", "may", "be", "overridden", "by", "a", "later", "call", "to", "read", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfig.go#L38-L46
train
trivago/gollum
core/pluginconfig.go
NewNestedPluginConfig
func NewNestedPluginConfig(defaultTypename string, values tcontainer.MarshalMap) (PluginConfig, error) { conf := NewPluginConfig("", defaultTypename) err := conf.Read(values) return conf, err }
go
func NewNestedPluginConfig(defaultTypename string, values tcontainer.MarshalMap) (PluginConfig, error) { conf := NewPluginConfig("", defaultTypename) err := conf.Read(values) return conf, err }
[ "func", "NewNestedPluginConfig", "(", "defaultTypename", "string", ",", "values", "tcontainer", ".", "MarshalMap", ")", "(", "PluginConfig", ",", "error", ")", "{", "conf", ":=", "NewPluginConfig", "(", "\"", "\"", ",", "defaultTypename", ")", "\n", "err", ":=", "conf", ".", "Read", "(", "values", ")", "\n", "return", "conf", ",", "err", "\n", "}" ]
// NewNestedPluginConfig creates a pluginconfig based on a given set of config // values. The plugin created does not have an id, i.e. it is considered // anonymous.
[ "NewNestedPluginConfig", "creates", "a", "pluginconfig", "based", "on", "a", "given", "set", "of", "config", "values", ".", "The", "plugin", "created", "does", "not", "have", "an", "id", "i", ".", "e", ".", "it", "is", "considered", "anonymous", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfig.go#L51-L55
train
trivago/gollum
core/pluginconfig.go
registerKey
func (conf *PluginConfig) registerKey(key string) string { if _, exists := conf.validKeys[key]; exists { return key // ### return, already registered ### } // Remove array notation from path path := key startIdx := strings.IndexRune(path, tcontainer.MarshalMapArrayBegin) for startIdx > -1 { if endIdx := strings.IndexRune(path[startIdx:], tcontainer.MarshalMapArrayEnd); endIdx > -1 { path = path[0:startIdx] + path[startIdx+endIdx+1:] startIdx = strings.IndexRune(path, tcontainer.MarshalMapArrayBegin) } else { startIdx = -1 } } if _, exists := conf.validKeys[path]; exists { return key // ### return, already registered (without array notation) ### } // Register all parts of the path startIdx = strings.IndexRune(path, tcontainer.MarshalMapSeparator) cutIdx := startIdx for startIdx > -1 { conf.validKeys[path[:cutIdx]] = true startIdx = strings.IndexRune(path[startIdx+1:], tcontainer.MarshalMapSeparator) cutIdx += startIdx } conf.validKeys[path] = true return key }
go
func (conf *PluginConfig) registerKey(key string) string { if _, exists := conf.validKeys[key]; exists { return key // ### return, already registered ### } // Remove array notation from path path := key startIdx := strings.IndexRune(path, tcontainer.MarshalMapArrayBegin) for startIdx > -1 { if endIdx := strings.IndexRune(path[startIdx:], tcontainer.MarshalMapArrayEnd); endIdx > -1 { path = path[0:startIdx] + path[startIdx+endIdx+1:] startIdx = strings.IndexRune(path, tcontainer.MarshalMapArrayBegin) } else { startIdx = -1 } } if _, exists := conf.validKeys[path]; exists { return key // ### return, already registered (without array notation) ### } // Register all parts of the path startIdx = strings.IndexRune(path, tcontainer.MarshalMapSeparator) cutIdx := startIdx for startIdx > -1 { conf.validKeys[path[:cutIdx]] = true startIdx = strings.IndexRune(path[startIdx+1:], tcontainer.MarshalMapSeparator) cutIdx += startIdx } conf.validKeys[path] = true return key }
[ "func", "(", "conf", "*", "PluginConfig", ")", "registerKey", "(", "key", "string", ")", "string", "{", "if", "_", ",", "exists", ":=", "conf", ".", "validKeys", "[", "key", "]", ";", "exists", "{", "return", "key", "// ### return, already registered ###", "\n", "}", "\n\n", "// Remove array notation from path", "path", ":=", "key", "\n", "startIdx", ":=", "strings", ".", "IndexRune", "(", "path", ",", "tcontainer", ".", "MarshalMapArrayBegin", ")", "\n", "for", "startIdx", ">", "-", "1", "{", "if", "endIdx", ":=", "strings", ".", "IndexRune", "(", "path", "[", "startIdx", ":", "]", ",", "tcontainer", ".", "MarshalMapArrayEnd", ")", ";", "endIdx", ">", "-", "1", "{", "path", "=", "path", "[", "0", ":", "startIdx", "]", "+", "path", "[", "startIdx", "+", "endIdx", "+", "1", ":", "]", "\n", "startIdx", "=", "strings", ".", "IndexRune", "(", "path", ",", "tcontainer", ".", "MarshalMapArrayBegin", ")", "\n", "}", "else", "{", "startIdx", "=", "-", "1", "\n", "}", "\n", "}", "\n\n", "if", "_", ",", "exists", ":=", "conf", ".", "validKeys", "[", "path", "]", ";", "exists", "{", "return", "key", "// ### return, already registered (without array notation) ###", "\n", "}", "\n\n", "// Register all parts of the path", "startIdx", "=", "strings", ".", "IndexRune", "(", "path", ",", "tcontainer", ".", "MarshalMapSeparator", ")", "\n", "cutIdx", ":=", "startIdx", "\n", "for", "startIdx", ">", "-", "1", "{", "conf", ".", "validKeys", "[", "path", "[", ":", "cutIdx", "]", "]", "=", "true", "\n", "startIdx", "=", "strings", ".", "IndexRune", "(", "path", "[", "startIdx", "+", "1", ":", "]", ",", "tcontainer", ".", "MarshalMapSeparator", ")", "\n", "cutIdx", "+=", "startIdx", "\n", "}", "\n\n", "conf", ".", "validKeys", "[", "path", "]", "=", "true", "\n", "return", "key", "\n", "}" ]
// registerKey registers a key to the validKeys map as lowercase and returns // the lowercase key
[ "registerKey", "registers", "a", "key", "to", "the", "validKeys", "map", "as", "lowercase", "and", "returns", "the", "lowercase", "key" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfig.go#L59-L91
train
trivago/gollum
core/pluginconfig.go
Validate
func (conf PluginConfig) Validate() error { errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) for key := range conf.Settings { if _, exists := conf.validKeys[key]; !exists { if suggestion := conf.suggestKey(key); suggestion != "" { errors.Pushf("Unknown configuration key '%s' in '%s'. Did you mean '%s'?", key, conf.Typename, suggestion) } else { errors.Pushf("Unknown configuration key '%s' in '%s", key, conf.Typename) } } } return errors.OrNil() }
go
func (conf PluginConfig) Validate() error { errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) for key := range conf.Settings { if _, exists := conf.validKeys[key]; !exists { if suggestion := conf.suggestKey(key); suggestion != "" { errors.Pushf("Unknown configuration key '%s' in '%s'. Did you mean '%s'?", key, conf.Typename, suggestion) } else { errors.Pushf("Unknown configuration key '%s' in '%s", key, conf.Typename) } } } return errors.OrNil() }
[ "func", "(", "conf", "PluginConfig", ")", "Validate", "(", ")", "error", "{", "errors", ":=", "tgo", ".", "NewErrorStack", "(", ")", "\n", "errors", ".", "SetFormat", "(", "tgo", ".", "ErrorStackFormatCSV", ")", "\n", "for", "key", ":=", "range", "conf", ".", "Settings", "{", "if", "_", ",", "exists", ":=", "conf", ".", "validKeys", "[", "key", "]", ";", "!", "exists", "{", "if", "suggestion", ":=", "conf", ".", "suggestKey", "(", "key", ")", ";", "suggestion", "!=", "\"", "\"", "{", "errors", ".", "Pushf", "(", "\"", "\"", ",", "key", ",", "conf", ".", "Typename", ",", "suggestion", ")", "\n", "}", "else", "{", "errors", ".", "Pushf", "(", "\"", "\"", ",", "key", ",", "conf", ".", "Typename", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "OrNil", "(", ")", "\n", "}" ]
// Validate should be called after a configuration has been processed. It will // check the keys read from the config files against the keys requested up to // this point. Unknown keys will be returned as errors
[ "Validate", "should", "be", "called", "after", "a", "configuration", "has", "been", "processed", ".", "It", "will", "check", "the", "keys", "read", "from", "the", "config", "files", "against", "the", "keys", "requested", "up", "to", "this", "point", ".", "Unknown", "keys", "will", "be", "returned", "as", "errors" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfig.go#L116-L129
train
trivago/gollum
core/pluginconfig.go
Override
func (conf *PluginConfig) Override(key string, value interface{}) { key = conf.registerKey(key) conf.Settings[key] = value }
go
func (conf *PluginConfig) Override(key string, value interface{}) { key = conf.registerKey(key) conf.Settings[key] = value }
[ "func", "(", "conf", "*", "PluginConfig", ")", "Override", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "{", "key", "=", "conf", ".", "registerKey", "(", "key", ")", "\n", "conf", ".", "Settings", "[", "key", "]", "=", "value", "\n", "}" ]
// Override sets or override a configuration value for non-predefined options.
[ "Override", "sets", "or", "override", "a", "configuration", "value", "for", "non", "-", "predefined", "options", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginconfig.go#L206-L209
train
trivago/gollum
router/distribute.go
Start
func (router *Distribute) Start() error { for _, streamID := range router.boundStreamIDs { targetRouter := core.StreamRegistry.GetRouterOrFallback(streamID) router.routers = append(router.routers, targetRouter) } return nil }
go
func (router *Distribute) Start() error { for _, streamID := range router.boundStreamIDs { targetRouter := core.StreamRegistry.GetRouterOrFallback(streamID) router.routers = append(router.routers, targetRouter) } return nil }
[ "func", "(", "router", "*", "Distribute", ")", "Start", "(", ")", "error", "{", "for", "_", ",", "streamID", ":=", "range", "router", ".", "boundStreamIDs", "{", "targetRouter", ":=", "core", ".", "StreamRegistry", ".", "GetRouterOrFallback", "(", "streamID", ")", "\n", "router", ".", "routers", "=", "append", "(", "router", ".", "routers", ",", "targetRouter", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Start the router
[ "Start", "the", "router" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/router/distribute.go#L66-L72
train
trivago/gollum
core/streamregistry.go
GetStreamID
func (registry *streamRegistry) GetStreamID(stream string) MessageStreamID { hash := fnv.New64a() hash.Write([]byte(stream)) streamID := MessageStreamID(hash.Sum64()) registry.nameGuard.Lock() registry.name[streamID] = stream registry.nameGuard.Unlock() return streamID }
go
func (registry *streamRegistry) GetStreamID(stream string) MessageStreamID { hash := fnv.New64a() hash.Write([]byte(stream)) streamID := MessageStreamID(hash.Sum64()) registry.nameGuard.Lock() registry.name[streamID] = stream registry.nameGuard.Unlock() return streamID }
[ "func", "(", "registry", "*", "streamRegistry", ")", "GetStreamID", "(", "stream", "string", ")", "MessageStreamID", "{", "hash", ":=", "fnv", ".", "New64a", "(", ")", "\n", "hash", ".", "Write", "(", "[", "]", "byte", "(", "stream", ")", ")", "\n", "streamID", ":=", "MessageStreamID", "(", "hash", ".", "Sum64", "(", ")", ")", "\n\n", "registry", ".", "nameGuard", ".", "Lock", "(", ")", "\n", "registry", ".", "name", "[", "streamID", "]", "=", "stream", "\n", "registry", ".", "nameGuard", ".", "Unlock", "(", ")", "\n\n", "return", "streamID", "\n", "}" ]
// GetStreamID returns the integer representation of a given stream name.
[ "GetStreamID", "returns", "the", "integer", "representation", "of", "a", "given", "stream", "name", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L59-L69
train
trivago/gollum
core/streamregistry.go
GetStreamName
func (registry streamRegistry) GetStreamName(streamID MessageStreamID) string { switch streamID { case LogInternalStreamID: return LogInternalStream case WildcardStreamID: return WildcardStream case InvalidStreamID: return InvalidStream case TraceInternalStreamID: return TraceInternalStream default: registry.nameGuard.RLock() name, exists := registry.name[streamID] registry.nameGuard.RUnlock() if exists { return name // ### return, found ### } } return "" }
go
func (registry streamRegistry) GetStreamName(streamID MessageStreamID) string { switch streamID { case LogInternalStreamID: return LogInternalStream case WildcardStreamID: return WildcardStream case InvalidStreamID: return InvalidStream case TraceInternalStreamID: return TraceInternalStream default: registry.nameGuard.RLock() name, exists := registry.name[streamID] registry.nameGuard.RUnlock() if exists { return name // ### return, found ### } } return "" }
[ "func", "(", "registry", "streamRegistry", ")", "GetStreamName", "(", "streamID", "MessageStreamID", ")", "string", "{", "switch", "streamID", "{", "case", "LogInternalStreamID", ":", "return", "LogInternalStream", "\n\n", "case", "WildcardStreamID", ":", "return", "WildcardStream", "\n\n", "case", "InvalidStreamID", ":", "return", "InvalidStream", "\n\n", "case", "TraceInternalStreamID", ":", "return", "TraceInternalStream", "\n\n", "default", ":", "registry", ".", "nameGuard", ".", "RLock", "(", ")", "\n", "name", ",", "exists", ":=", "registry", ".", "name", "[", "streamID", "]", "\n", "registry", ".", "nameGuard", ".", "RUnlock", "(", ")", "\n\n", "if", "exists", "{", "return", "name", "// ### return, found ###", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// GetStreamName does a reverse lookup for a given MessageStreamID and returns // the corresponding name. If the MessageStreamID is not registered, an empty // string is returned.
[ "GetStreamName", "does", "a", "reverse", "lookup", "for", "a", "given", "MessageStreamID", "and", "returns", "the", "corresponding", "name", ".", "If", "the", "MessageStreamID", "is", "not", "registered", "an", "empty", "string", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L74-L98
train
trivago/gollum
core/streamregistry.go
GetRouterByStreamName
func (registry streamRegistry) GetRouterByStreamName(name string) Router { streamID := registry.GetStreamID(name) return registry.GetRouter(streamID) }
go
func (registry streamRegistry) GetRouterByStreamName(name string) Router { streamID := registry.GetStreamID(name) return registry.GetRouter(streamID) }
[ "func", "(", "registry", "streamRegistry", ")", "GetRouterByStreamName", "(", "name", "string", ")", "Router", "{", "streamID", ":=", "registry", ".", "GetStreamID", "(", "name", ")", "\n", "return", "registry", ".", "GetRouter", "(", "streamID", ")", "\n", "}" ]
// GetRouterByStreamName returns a registered stream by name. See GetRouter.
[ "GetRouterByStreamName", "returns", "a", "registered", "stream", "by", "name", ".", "See", "GetRouter", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L101-L104
train
trivago/gollum
core/streamregistry.go
GetRouter
func (registry streamRegistry) GetRouter(id MessageStreamID) Router { registry.streamGuard.RLock() stream, exists := registry.routers[id] registry.streamGuard.RUnlock() if exists { return stream } return nil }
go
func (registry streamRegistry) GetRouter(id MessageStreamID) Router { registry.streamGuard.RLock() stream, exists := registry.routers[id] registry.streamGuard.RUnlock() if exists { return stream } return nil }
[ "func", "(", "registry", "streamRegistry", ")", "GetRouter", "(", "id", "MessageStreamID", ")", "Router", "{", "registry", ".", "streamGuard", ".", "RLock", "(", ")", "\n", "stream", ",", "exists", ":=", "registry", ".", "routers", "[", "id", "]", "\n", "registry", ".", "streamGuard", ".", "RUnlock", "(", ")", "\n\n", "if", "exists", "{", "return", "stream", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetRouter returns a registered stream or nil
[ "GetRouter", "returns", "a", "registered", "stream", "or", "nil" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L107-L116
train
trivago/gollum
core/streamregistry.go
IsStreamRegistered
func (registry streamRegistry) IsStreamRegistered(id MessageStreamID) bool { registry.streamGuard.RLock() _, exists := registry.routers[id] registry.streamGuard.RUnlock() return exists }
go
func (registry streamRegistry) IsStreamRegistered(id MessageStreamID) bool { registry.streamGuard.RLock() _, exists := registry.routers[id] registry.streamGuard.RUnlock() return exists }
[ "func", "(", "registry", "streamRegistry", ")", "IsStreamRegistered", "(", "id", "MessageStreamID", ")", "bool", "{", "registry", ".", "streamGuard", ".", "RLock", "(", ")", "\n", "_", ",", "exists", ":=", "registry", ".", "routers", "[", "id", "]", "\n", "registry", ".", "streamGuard", ".", "RUnlock", "(", ")", "\n\n", "return", "exists", "\n", "}" ]
// IsStreamRegistered returns true if the stream for the given id is registered.
[ "IsStreamRegistered", "returns", "true", "if", "the", "stream", "for", "the", "given", "id", "is", "registered", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L119-L125
train
trivago/gollum
core/streamregistry.go
ForEachStream
func (registry streamRegistry) ForEachStream(callback func(streamID MessageStreamID, stream Router)) { registry.streamGuard.RLock() defer registry.streamGuard.RUnlock() for streamID, router := range registry.routers { callback(streamID, router) } }
go
func (registry streamRegistry) ForEachStream(callback func(streamID MessageStreamID, stream Router)) { registry.streamGuard.RLock() defer registry.streamGuard.RUnlock() for streamID, router := range registry.routers { callback(streamID, router) } }
[ "func", "(", "registry", "streamRegistry", ")", "ForEachStream", "(", "callback", "func", "(", "streamID", "MessageStreamID", ",", "stream", "Router", ")", ")", "{", "registry", ".", "streamGuard", ".", "RLock", "(", ")", "\n", "defer", "registry", ".", "streamGuard", ".", "RUnlock", "(", ")", "\n\n", "for", "streamID", ",", "router", ":=", "range", "registry", ".", "routers", "{", "callback", "(", "streamID", ",", "router", ")", "\n", "}", "\n", "}" ]
// ForEachStream loops over all registered routers and calls the given function.
[ "ForEachStream", "loops", "over", "all", "registered", "routers", "and", "calls", "the", "given", "function", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L128-L135
train
trivago/gollum
core/streamregistry.go
AddWildcardProducersToRouter
func (registry streamRegistry) AddWildcardProducersToRouter(router Router) { streamID := router.GetStreamID() if streamID != LogInternalStreamID { router.AddProducer(registry.wildcard...) } }
go
func (registry streamRegistry) AddWildcardProducersToRouter(router Router) { streamID := router.GetStreamID() if streamID != LogInternalStreamID { router.AddProducer(registry.wildcard...) } }
[ "func", "(", "registry", "streamRegistry", ")", "AddWildcardProducersToRouter", "(", "router", "Router", ")", "{", "streamID", ":=", "router", ".", "GetStreamID", "(", ")", "\n", "if", "streamID", "!=", "LogInternalStreamID", "{", "router", ".", "AddProducer", "(", "registry", ".", "wildcard", "...", ")", "\n", "}", "\n", "}" ]
// AddWildcardProducersToRouter adds all known wildcard producers to a given // router. The state of the wildcard list is undefined during the configuration // phase.
[ "AddWildcardProducersToRouter", "adds", "all", "known", "wildcard", "producers", "to", "a", "given", "router", ".", "The", "state", "of", "the", "wildcard", "list", "is", "undefined", "during", "the", "configuration", "phase", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L163-L168
train
trivago/gollum
core/streamregistry.go
AddAllWildcardProducersToAllRouters
func (registry *streamRegistry) AddAllWildcardProducersToAllRouters() { registry.ForEachStream( func(streamID MessageStreamID, router Router) { registry.AddWildcardProducersToRouter(router) }) }
go
func (registry *streamRegistry) AddAllWildcardProducersToAllRouters() { registry.ForEachStream( func(streamID MessageStreamID, router Router) { registry.AddWildcardProducersToRouter(router) }) }
[ "func", "(", "registry", "*", "streamRegistry", ")", "AddAllWildcardProducersToAllRouters", "(", ")", "{", "registry", ".", "ForEachStream", "(", "func", "(", "streamID", "MessageStreamID", ",", "router", "Router", ")", "{", "registry", ".", "AddWildcardProducersToRouter", "(", "router", ")", "\n", "}", ")", "\n", "}" ]
// AddAllWildcardProducersToAllRouters executes AddWildcardProducersToRouter on // all currently registered routers
[ "AddAllWildcardProducersToAllRouters", "executes", "AddWildcardProducersToRouter", "on", "all", "currently", "registered", "routers" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L172-L177
train
trivago/gollum
core/streamregistry.go
Register
func (registry *streamRegistry) Register(router Router, streamID MessageStreamID) { registry.streamGuard.RLock() _, exists := registry.routers[streamID] registry.streamGuard.RUnlock() if exists { logrus.Warningf("%T attaches to an already occupied router (%s)", router, registry.GetStreamName(streamID)) return // ### return, double registration ### } registry.streamGuard.Lock() defer registry.streamGuard.Unlock() // Test again inside critical section to avoid races if _, exists := registry.routers[streamID]; !exists { registry.routers[streamID] = router MetricRouters.Inc(1) } }
go
func (registry *streamRegistry) Register(router Router, streamID MessageStreamID) { registry.streamGuard.RLock() _, exists := registry.routers[streamID] registry.streamGuard.RUnlock() if exists { logrus.Warningf("%T attaches to an already occupied router (%s)", router, registry.GetStreamName(streamID)) return // ### return, double registration ### } registry.streamGuard.Lock() defer registry.streamGuard.Unlock() // Test again inside critical section to avoid races if _, exists := registry.routers[streamID]; !exists { registry.routers[streamID] = router MetricRouters.Inc(1) } }
[ "func", "(", "registry", "*", "streamRegistry", ")", "Register", "(", "router", "Router", ",", "streamID", "MessageStreamID", ")", "{", "registry", ".", "streamGuard", ".", "RLock", "(", ")", "\n", "_", ",", "exists", ":=", "registry", ".", "routers", "[", "streamID", "]", "\n", "registry", ".", "streamGuard", ".", "RUnlock", "(", ")", "\n\n", "if", "exists", "{", "logrus", ".", "Warningf", "(", "\"", "\"", ",", "router", ",", "registry", ".", "GetStreamName", "(", "streamID", ")", ")", "\n", "return", "// ### return, double registration ###", "\n", "}", "\n\n", "registry", ".", "streamGuard", ".", "Lock", "(", ")", "\n", "defer", "registry", ".", "streamGuard", ".", "Unlock", "(", ")", "\n\n", "// Test again inside critical section to avoid races", "if", "_", ",", "exists", ":=", "registry", ".", "routers", "[", "streamID", "]", ";", "!", "exists", "{", "registry", ".", "routers", "[", "streamID", "]", "=", "router", "\n", "MetricRouters", ".", "Inc", "(", "1", ")", "\n", "}", "\n", "}" ]
// Register registers a router plugin to a given stream id
[ "Register", "registers", "a", "router", "plugin", "to", "a", "given", "stream", "id" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L180-L198
train
trivago/gollum
core/streamregistry.go
GetRouterOrFallback
func (registry *streamRegistry) GetRouterOrFallback(streamID MessageStreamID) Router { if streamID == InvalidStreamID { return nil // ### return, invalid stream does not have a router ### } registry.streamGuard.RLock() router, exists := registry.routers[streamID] registry.streamGuard.RUnlock() if exists { return router // ### return, already registered ### } registry.streamGuard.Lock() defer registry.streamGuard.Unlock() // Create router, avoid race conditions by check again in ciritical section if router, exists = registry.routers[streamID]; exists { return router // ### return, lost the race ### } defaultRouter := registry.createFallback(streamID) registry.AddWildcardProducersToRouter(defaultRouter) registry.routers[streamID] = defaultRouter MetricRouters.Inc(1) MetricFallbackRouters.Inc(1) return defaultRouter }
go
func (registry *streamRegistry) GetRouterOrFallback(streamID MessageStreamID) Router { if streamID == InvalidStreamID { return nil // ### return, invalid stream does not have a router ### } registry.streamGuard.RLock() router, exists := registry.routers[streamID] registry.streamGuard.RUnlock() if exists { return router // ### return, already registered ### } registry.streamGuard.Lock() defer registry.streamGuard.Unlock() // Create router, avoid race conditions by check again in ciritical section if router, exists = registry.routers[streamID]; exists { return router // ### return, lost the race ### } defaultRouter := registry.createFallback(streamID) registry.AddWildcardProducersToRouter(defaultRouter) registry.routers[streamID] = defaultRouter MetricRouters.Inc(1) MetricFallbackRouters.Inc(1) return defaultRouter }
[ "func", "(", "registry", "*", "streamRegistry", ")", "GetRouterOrFallback", "(", "streamID", "MessageStreamID", ")", "Router", "{", "if", "streamID", "==", "InvalidStreamID", "{", "return", "nil", "// ### return, invalid stream does not have a router ###", "\n", "}", "\n\n", "registry", ".", "streamGuard", ".", "RLock", "(", ")", "\n", "router", ",", "exists", ":=", "registry", ".", "routers", "[", "streamID", "]", "\n", "registry", ".", "streamGuard", ".", "RUnlock", "(", ")", "\n", "if", "exists", "{", "return", "router", "// ### return, already registered ###", "\n", "}", "\n\n", "registry", ".", "streamGuard", ".", "Lock", "(", ")", "\n", "defer", "registry", ".", "streamGuard", ".", "Unlock", "(", ")", "\n\n", "// Create router, avoid race conditions by check again in ciritical section", "if", "router", ",", "exists", "=", "registry", ".", "routers", "[", "streamID", "]", ";", "exists", "{", "return", "router", "// ### return, lost the race ###", "\n", "}", "\n\n", "defaultRouter", ":=", "registry", ".", "createFallback", "(", "streamID", ")", "\n", "registry", ".", "AddWildcardProducersToRouter", "(", "defaultRouter", ")", "\n", "registry", ".", "routers", "[", "streamID", "]", "=", "defaultRouter", "\n\n", "MetricRouters", ".", "Inc", "(", "1", ")", "\n", "MetricFallbackRouters", ".", "Inc", "(", "1", ")", "\n\n", "return", "defaultRouter", "\n", "}" ]
// GetRouterOrFallback returns the router for the given streamID if it is registered. // If no router is registered for the given streamID the default router is used. // The default router is equivalent to an unconfigured router.Broadcast with // all wildcard producers already added.
[ "GetRouterOrFallback", "returns", "the", "router", "for", "the", "given", "streamID", "if", "it", "is", "registered", ".", "If", "no", "router", "is", "registered", "for", "the", "given", "streamID", "the", "default", "router", "is", "used", ".", "The", "default", "router", "is", "equivalent", "to", "an", "unconfigured", "router", ".", "Broadcast", "with", "all", "wildcard", "producers", "already", "added", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/streamregistry.go#L204-L232
train
trivago/gollum
core/metadata.go
SetValue
func (meta Metadata) SetValue(key string, value []byte) { meta[key] = value }
go
func (meta Metadata) SetValue(key string, value []byte) { meta[key] = value }
[ "func", "(", "meta", "Metadata", ")", "SetValue", "(", "key", "string", ",", "value", "[", "]", "byte", ")", "{", "meta", "[", "key", "]", "=", "value", "\n", "}" ]
// SetValue set a key value pair at meta data
[ "SetValue", "set", "a", "key", "value", "pair", "at", "meta", "data" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L21-L23
train
trivago/gollum
core/metadata.go
TrySetValue
func (meta Metadata) TrySetValue(key string, value []byte) bool { if _, exists := meta[key]; exists { meta[key] = value return true } return false }
go
func (meta Metadata) TrySetValue(key string, value []byte) bool { if _, exists := meta[key]; exists { meta[key] = value return true } return false }
[ "func", "(", "meta", "Metadata", ")", "TrySetValue", "(", "key", "string", ",", "value", "[", "]", "byte", ")", "bool", "{", "if", "_", ",", "exists", ":=", "meta", "[", "key", "]", ";", "exists", "{", "meta", "[", "key", "]", "=", "value", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// TrySetValue sets a key value pair only if the key is already existing
[ "TrySetValue", "sets", "a", "key", "value", "pair", "only", "if", "the", "key", "is", "already", "existing" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L26-L32
train
trivago/gollum
core/metadata.go
GetValue
func (meta Metadata) GetValue(key string) []byte { if value, isSet := meta[key]; isSet { return value } return []byte{} }
go
func (meta Metadata) GetValue(key string) []byte { if value, isSet := meta[key]; isSet { return value } return []byte{} }
[ "func", "(", "meta", "Metadata", ")", "GetValue", "(", "key", "string", ")", "[", "]", "byte", "{", "if", "value", ",", "isSet", ":=", "meta", "[", "key", "]", ";", "isSet", "{", "return", "value", "\n", "}", "\n\n", "return", "[", "]", "byte", "{", "}", "\n", "}" ]
// GetValue returns a meta data value by key. This function returns a value if // key is not set, too. In that case it will return an empty byte array.
[ "GetValue", "returns", "a", "meta", "data", "value", "by", "key", ".", "This", "function", "returns", "a", "value", "if", "key", "is", "not", "set", "too", ".", "In", "that", "case", "it", "will", "return", "an", "empty", "byte", "array", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L36-L42
train
trivago/gollum
core/metadata.go
TryGetValue
func (meta Metadata) TryGetValue(key string) ([]byte, bool) { if value, isSet := meta[key]; isSet { return value, true } return []byte{}, false }
go
func (meta Metadata) TryGetValue(key string) ([]byte, bool) { if value, isSet := meta[key]; isSet { return value, true } return []byte{}, false }
[ "func", "(", "meta", "Metadata", ")", "TryGetValue", "(", "key", "string", ")", "(", "[", "]", "byte", ",", "bool", ")", "{", "if", "value", ",", "isSet", ":=", "meta", "[", "key", "]", ";", "isSet", "{", "return", "value", ",", "true", "\n", "}", "\n", "return", "[", "]", "byte", "{", "}", ",", "false", "\n", "}" ]
// TryGetValue behaves like GetValue but returns a second value which denotes // if the key was set or not.
[ "TryGetValue", "behaves", "like", "GetValue", "but", "returns", "a", "second", "value", "which", "denotes", "if", "the", "key", "was", "set", "or", "not", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L46-L51
train
trivago/gollum
core/metadata.go
GetValueString
func (meta Metadata) GetValueString(key string) string { return string(meta.GetValue(key)) }
go
func (meta Metadata) GetValueString(key string) string { return string(meta.GetValue(key)) }
[ "func", "(", "meta", "Metadata", ")", "GetValueString", "(", "key", "string", ")", "string", "{", "return", "string", "(", "meta", ".", "GetValue", "(", "key", ")", ")", "\n", "}" ]
// GetValueString casts the results of GetValue to a string
[ "GetValueString", "casts", "the", "results", "of", "GetValue", "to", "a", "string" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L54-L56
train
trivago/gollum
core/metadata.go
TryGetValueString
func (meta Metadata) TryGetValueString(key string) (string, bool) { data, exists := meta.TryGetValue(key) return string(data), exists }
go
func (meta Metadata) TryGetValueString(key string) (string, bool) { data, exists := meta.TryGetValue(key) return string(data), exists }
[ "func", "(", "meta", "Metadata", ")", "TryGetValueString", "(", "key", "string", ")", "(", "string", ",", "bool", ")", "{", "data", ",", "exists", ":=", "meta", ".", "TryGetValue", "(", "key", ")", "\n", "return", "string", "(", "data", ")", ",", "exists", "\n", "}" ]
// TryGetValueString casts the data result of TryGetValue to string
[ "TryGetValueString", "casts", "the", "data", "result", "of", "TryGetValue", "to", "string" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L59-L62
train
trivago/gollum
core/metadata.go
Clone
func (meta Metadata) Clone() (clone Metadata) { clone = Metadata{} for k, v := range meta { vCopy := make([]byte, len(v)) copy(vCopy, v) clone[k] = vCopy } return }
go
func (meta Metadata) Clone() (clone Metadata) { clone = Metadata{} for k, v := range meta { vCopy := make([]byte, len(v)) copy(vCopy, v) clone[k] = vCopy } return }
[ "func", "(", "meta", "Metadata", ")", "Clone", "(", ")", "(", "clone", "Metadata", ")", "{", "clone", "=", "Metadata", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "meta", "{", "vCopy", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "v", ")", ")", "\n", "copy", "(", "vCopy", ",", "v", ")", "\n", "clone", "[", "k", "]", "=", "vCopy", "\n", "}", "\n", "return", "\n", "}" ]
// Clone creates an exact copy of this metadata map.
[ "Clone", "creates", "an", "exact", "copy", "of", "this", "metadata", "map", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/metadata.go#L70-L78
train
trivago/gollum
core/simpleproducer.go
Modulate
func (prod *SimpleProducer) Modulate(msg *Message) ModulateResult { if len(prod.modulators) > 0 { msg.FreezeOriginal() return prod.modulators.Modulate(msg) } return ModulateResultContinue }
go
func (prod *SimpleProducer) Modulate(msg *Message) ModulateResult { if len(prod.modulators) > 0 { msg.FreezeOriginal() return prod.modulators.Modulate(msg) } return ModulateResultContinue }
[ "func", "(", "prod", "*", "SimpleProducer", ")", "Modulate", "(", "msg", "*", "Message", ")", "ModulateResult", "{", "if", "len", "(", "prod", ".", "modulators", ")", ">", "0", "{", "msg", ".", "FreezeOriginal", "(", ")", "\n", "return", "prod", ".", "modulators", ".", "Modulate", "(", "msg", ")", "\n", "}", "\n", "return", "ModulateResultContinue", "\n", "}" ]
// Modulate applies all modulators from this producer to a given message. // This implementation handles routing and discarding of messages.
[ "Modulate", "applies", "all", "modulators", "from", "this", "producer", "to", "a", "given", "message", ".", "This", "implementation", "handles", "routing", "and", "discarding", "of", "messages", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleproducer.go#L191-L197
train
trivago/gollum
core/simpleproducer.go
HasContinueAfterModulate
func (prod *SimpleProducer) HasContinueAfterModulate(msg *Message) bool { switch result := prod.Modulate(msg); result { case ModulateResultDiscard: DiscardMessage(msg, prod.GetID(), "Producer discarded") return false case ModulateResultFallback: if err := Route(msg, msg.GetRouter()); err != nil { prod.Logger.WithError(err).Error("Failed to route to fallback") } return false case ModulateResultContinue: // OK return true default: prod.Logger.Error("Modulator result not supported:", result) return false } }
go
func (prod *SimpleProducer) HasContinueAfterModulate(msg *Message) bool { switch result := prod.Modulate(msg); result { case ModulateResultDiscard: DiscardMessage(msg, prod.GetID(), "Producer discarded") return false case ModulateResultFallback: if err := Route(msg, msg.GetRouter()); err != nil { prod.Logger.WithError(err).Error("Failed to route to fallback") } return false case ModulateResultContinue: // OK return true default: prod.Logger.Error("Modulator result not supported:", result) return false } }
[ "func", "(", "prod", "*", "SimpleProducer", ")", "HasContinueAfterModulate", "(", "msg", "*", "Message", ")", "bool", "{", "switch", "result", ":=", "prod", ".", "Modulate", "(", "msg", ")", ";", "result", "{", "case", "ModulateResultDiscard", ":", "DiscardMessage", "(", "msg", ",", "prod", ".", "GetID", "(", ")", ",", "\"", "\"", ")", "\n", "return", "false", "\n\n", "case", "ModulateResultFallback", ":", "if", "err", ":=", "Route", "(", "msg", ",", "msg", ".", "GetRouter", "(", ")", ")", ";", "err", "!=", "nil", "{", "prod", ".", "Logger", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "false", "\n\n", "case", "ModulateResultContinue", ":", "// OK", "return", "true", "\n\n", "default", ":", "prod", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "result", ")", "\n", "return", "false", "\n", "}", "\n", "}" ]
// HasContinueAfterModulate applies all modulators by Modulate, handle the ModulateResult // and return if you have to continue the message process. // This method is a default producer modulate handling.
[ "HasContinueAfterModulate", "applies", "all", "modulators", "by", "Modulate", "handle", "the", "ModulateResult", "and", "return", "if", "you", "have", "to", "continue", "the", "message", "process", ".", "This", "method", "is", "a", "default", "producer", "modulate", "handling", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleproducer.go#L202-L222
train
trivago/gollum
core/simpleproducer.go
TryFallback
func (prod *SimpleProducer) TryFallback(msg *Message) { if err := RouteOriginal(msg, prod.fallbackStream); err != nil { prod.Logger.WithError(err).Error("Failed to route to fallback") } }
go
func (prod *SimpleProducer) TryFallback(msg *Message) { if err := RouteOriginal(msg, prod.fallbackStream); err != nil { prod.Logger.WithError(err).Error("Failed to route to fallback") } }
[ "func", "(", "prod", "*", "SimpleProducer", ")", "TryFallback", "(", "msg", "*", "Message", ")", "{", "if", "err", ":=", "RouteOriginal", "(", "msg", ",", "prod", ".", "fallbackStream", ")", ";", "err", "!=", "nil", "{", "prod", ".", "Logger", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// TryFallback routes the message to the configured fallback stream.
[ "TryFallback", "routes", "the", "message", "to", "the", "configured", "fallback", "stream", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleproducer.go#L225-L229
train
trivago/gollum
core/simpleproducer.go
ControlLoop
func (prod *SimpleProducer) ControlLoop() { prod.setState(PluginStateActive) defer prod.setState(PluginStateDead) defer prod.Logger.Debug("Stopped") for { command := <-prod.control switch command { default: prod.Logger.Debug("Received untracked command") // Do nothing case PluginControlStopProducer: prod.Logger.Debug("Preparing for stop") prod.setState(PluginStatePrepareStop) if prod.onPrepareStop != nil { if !tgo.ReturnAfter(prod.shutdownTimeout*5, prod.onPrepareStop) { prod.Logger.Error("Timeout during onPrepareStop.") } } prod.Logger.Debug("Executing stop command") prod.setState(PluginStateStopping) if prod.onStop != nil { if !tgo.ReturnAfter(prod.shutdownTimeout*5, prod.onStop) { prod.Logger.Error("Timeout during onStop.") } } return // ### return ### case PluginControlRoll: prod.Logger.Debug("Received roll command") if prod.onRoll != nil { prod.onRoll() } } } }
go
func (prod *SimpleProducer) ControlLoop() { prod.setState(PluginStateActive) defer prod.setState(PluginStateDead) defer prod.Logger.Debug("Stopped") for { command := <-prod.control switch command { default: prod.Logger.Debug("Received untracked command") // Do nothing case PluginControlStopProducer: prod.Logger.Debug("Preparing for stop") prod.setState(PluginStatePrepareStop) if prod.onPrepareStop != nil { if !tgo.ReturnAfter(prod.shutdownTimeout*5, prod.onPrepareStop) { prod.Logger.Error("Timeout during onPrepareStop.") } } prod.Logger.Debug("Executing stop command") prod.setState(PluginStateStopping) if prod.onStop != nil { if !tgo.ReturnAfter(prod.shutdownTimeout*5, prod.onStop) { prod.Logger.Error("Timeout during onStop.") } } return // ### return ### case PluginControlRoll: prod.Logger.Debug("Received roll command") if prod.onRoll != nil { prod.onRoll() } } } }
[ "func", "(", "prod", "*", "SimpleProducer", ")", "ControlLoop", "(", ")", "{", "prod", ".", "setState", "(", "PluginStateActive", ")", "\n", "defer", "prod", ".", "setState", "(", "PluginStateDead", ")", "\n", "defer", "prod", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "for", "{", "command", ":=", "<-", "prod", ".", "control", "\n", "switch", "command", "{", "default", ":", "prod", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "// Do nothing", "case", "PluginControlStopProducer", ":", "prod", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "prod", ".", "setState", "(", "PluginStatePrepareStop", ")", "\n\n", "if", "prod", ".", "onPrepareStop", "!=", "nil", "{", "if", "!", "tgo", ".", "ReturnAfter", "(", "prod", ".", "shutdownTimeout", "*", "5", ",", "prod", ".", "onPrepareStop", ")", "{", "prod", ".", "Logger", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "prod", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "prod", ".", "setState", "(", "PluginStateStopping", ")", "\n\n", "if", "prod", ".", "onStop", "!=", "nil", "{", "if", "!", "tgo", ".", "ReturnAfter", "(", "prod", ".", "shutdownTimeout", "*", "5", ",", "prod", ".", "onStop", ")", "{", "prod", ".", "Logger", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "// ### return ###", "\n\n", "case", "PluginControlRoll", ":", "prod", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "if", "prod", ".", "onRoll", "!=", "nil", "{", "prod", ".", "onRoll", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// ControlLoop listens to the control channel and triggers callbacks for these // messags. Upon stop control message doExit will be set to true.
[ "ControlLoop", "listens", "to", "the", "control", "channel", "and", "triggers", "callbacks", "for", "these", "messags", ".", "Upon", "stop", "control", "message", "doExit", "will", "be", "set", "to", "true", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleproducer.go#L233-L272
train
trivago/gollum
core/simpleproducer.go
TickerControlLoop
func (prod *SimpleProducer) TickerControlLoop(interval time.Duration, onTimeOut func()) { prod.setState(PluginStateActive) go prod.ControlLoop() prod.tickerLoop(interval, onTimeOut) }
go
func (prod *SimpleProducer) TickerControlLoop(interval time.Duration, onTimeOut func()) { prod.setState(PluginStateActive) go prod.ControlLoop() prod.tickerLoop(interval, onTimeOut) }
[ "func", "(", "prod", "*", "SimpleProducer", ")", "TickerControlLoop", "(", "interval", "time", ".", "Duration", ",", "onTimeOut", "func", "(", ")", ")", "{", "prod", ".", "setState", "(", "PluginStateActive", ")", "\n", "go", "prod", ".", "ControlLoop", "(", ")", "\n", "prod", ".", "tickerLoop", "(", "interval", ",", "onTimeOut", ")", "\n", "}" ]
// TickerControlLoop is like ControlLoop but executes a given function at // every given interval tick, too. If the onTick function takes longer than // interval, the next tick will be delayed until onTick finishes.
[ "TickerControlLoop", "is", "like", "ControlLoop", "but", "executes", "a", "given", "function", "at", "every", "given", "interval", "tick", "too", ".", "If", "the", "onTick", "function", "takes", "longer", "than", "interval", "the", "next", "tick", "will", "be", "delayed", "until", "onTick", "finishes", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleproducer.go#L277-L281
train
trivago/gollum
producer/proxy.go
Produce
func (prod *Proxy) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) prod.MessageControlLoop(prod.sendMessage) }
go
func (prod *Proxy) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) prod.MessageControlLoop(prod.sendMessage) }
[ "func", "(", "prod", "*", "Proxy", ")", "Produce", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "prod", ".", "AddMainWorker", "(", "workers", ")", "\n", "prod", ".", "MessageControlLoop", "(", "prod", ".", "sendMessage", ")", "\n", "}" ]
// Produce writes to a buffer that is sent to a given Proxy.
[ "Produce", "writes", "to", "a", "buffer", "that", "is", "sent", "to", "a", "given", "Proxy", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/proxy.go#L213-L216
train
trivago/gollum
consumer/http.go
requestHandler
func (cons *HTTP) requestHandler(resp http.ResponseWriter, req *http.Request) { if cons.htpasswd != "" { if !cons.checkAuth(req) { resp.WriteHeader(http.StatusUnauthorized) return } } if cons.withHeaders { // Read the whole package requestBuffer := bytes.NewBuffer(nil) if err := req.Write(requestBuffer); err != nil { resp.WriteHeader(http.StatusBadRequest) cons.Logger.Error(err) return // ### return, missing body or bad write ### } cons.Enqueue(requestBuffer.Bytes()) resp.WriteHeader(http.StatusOK) } else { // Read only the message body if req.Body == nil { resp.WriteHeader(http.StatusBadRequest) return // ### return, missing body ### } body, err := ioutil.ReadAll(req.Body) if err != nil { resp.WriteHeader(http.StatusBadRequest) cons.Logger.Error(err) return // ### return, missing body or bad write ### } defer req.Body.Close() cons.Enqueue(body) resp.WriteHeader(http.StatusOK) } }
go
func (cons *HTTP) requestHandler(resp http.ResponseWriter, req *http.Request) { if cons.htpasswd != "" { if !cons.checkAuth(req) { resp.WriteHeader(http.StatusUnauthorized) return } } if cons.withHeaders { // Read the whole package requestBuffer := bytes.NewBuffer(nil) if err := req.Write(requestBuffer); err != nil { resp.WriteHeader(http.StatusBadRequest) cons.Logger.Error(err) return // ### return, missing body or bad write ### } cons.Enqueue(requestBuffer.Bytes()) resp.WriteHeader(http.StatusOK) } else { // Read only the message body if req.Body == nil { resp.WriteHeader(http.StatusBadRequest) return // ### return, missing body ### } body, err := ioutil.ReadAll(req.Body) if err != nil { resp.WriteHeader(http.StatusBadRequest) cons.Logger.Error(err) return // ### return, missing body or bad write ### } defer req.Body.Close() cons.Enqueue(body) resp.WriteHeader(http.StatusOK) } }
[ "func", "(", "cons", "*", "HTTP", ")", "requestHandler", "(", "resp", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "if", "cons", ".", "htpasswd", "!=", "\"", "\"", "{", "if", "!", "cons", ".", "checkAuth", "(", "req", ")", "{", "resp", ".", "WriteHeader", "(", "http", ".", "StatusUnauthorized", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "if", "cons", ".", "withHeaders", "{", "// Read the whole package", "requestBuffer", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "if", "err", ":=", "req", ".", "Write", "(", "requestBuffer", ")", ";", "err", "!=", "nil", "{", "resp", ".", "WriteHeader", "(", "http", ".", "StatusBadRequest", ")", "\n", "cons", ".", "Logger", ".", "Error", "(", "err", ")", "\n", "return", "// ### return, missing body or bad write ###", "\n", "}", "\n\n", "cons", ".", "Enqueue", "(", "requestBuffer", ".", "Bytes", "(", ")", ")", "\n", "resp", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "}", "else", "{", "// Read only the message body", "if", "req", ".", "Body", "==", "nil", "{", "resp", ".", "WriteHeader", "(", "http", ".", "StatusBadRequest", ")", "\n", "return", "// ### return, missing body ###", "\n", "}", "\n\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "req", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "resp", ".", "WriteHeader", "(", "http", ".", "StatusBadRequest", ")", "\n", "cons", ".", "Logger", ".", "Error", "(", "err", ")", "\n", "return", "// ### return, missing body or bad write ###", "\n", "}", "\n", "defer", "req", ".", "Body", ".", "Close", "(", ")", "\n\n", "cons", ".", "Enqueue", "(", "body", ")", "\n", "resp", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "}", "\n", "}" ]
// requestHandler will handle a single web request.
[ "requestHandler", "will", "handle", "a", "single", "web", "request", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/consumer/http.go#L124-L161
train
trivago/gollum
producer/InfluxDBWriter10.go
configure
func (writer *influxDBWriter10) configure(conf core.PluginConfigReader, prod *InfluxDB) error { writer.host = conf.GetString("Host", "localhost:8086") writer.username = conf.GetString("User", "") writer.password = conf.GetString("Password", "") writer.databaseTemplate = conf.GetString("Database", "default") writer.buffer = tio.NewByteStream(4096) writer.connectionUp = false writer.timeBasedDBName = conf.GetBool("TimeBasedName", true) writer.Control = prod.Control writer.logger = prod.Logger writer.writeURL = fmt.Sprintf("http://%s/write", writer.host) writer.queryURL = fmt.Sprintf("http://%s/query", writer.host) writer.pingURL = fmt.Sprintf("http://%s/ping", writer.host) writer.separator = '?' if writer.username != "" { credentials := fmt.Sprintf("?u=%s&p=%s", url.QueryEscape(writer.username), url.QueryEscape(writer.password)) writer.writeURL += credentials writer.queryURL += credentials writer.separator = '&' } writer.writeURL = fmt.Sprintf("%s%cprecision=ms", writer.writeURL, writer.separator) return conf.Errors.OrNil() }
go
func (writer *influxDBWriter10) configure(conf core.PluginConfigReader, prod *InfluxDB) error { writer.host = conf.GetString("Host", "localhost:8086") writer.username = conf.GetString("User", "") writer.password = conf.GetString("Password", "") writer.databaseTemplate = conf.GetString("Database", "default") writer.buffer = tio.NewByteStream(4096) writer.connectionUp = false writer.timeBasedDBName = conf.GetBool("TimeBasedName", true) writer.Control = prod.Control writer.logger = prod.Logger writer.writeURL = fmt.Sprintf("http://%s/write", writer.host) writer.queryURL = fmt.Sprintf("http://%s/query", writer.host) writer.pingURL = fmt.Sprintf("http://%s/ping", writer.host) writer.separator = '?' if writer.username != "" { credentials := fmt.Sprintf("?u=%s&p=%s", url.QueryEscape(writer.username), url.QueryEscape(writer.password)) writer.writeURL += credentials writer.queryURL += credentials writer.separator = '&' } writer.writeURL = fmt.Sprintf("%s%cprecision=ms", writer.writeURL, writer.separator) return conf.Errors.OrNil() }
[ "func", "(", "writer", "*", "influxDBWriter10", ")", "configure", "(", "conf", "core", ".", "PluginConfigReader", ",", "prod", "*", "InfluxDB", ")", "error", "{", "writer", ".", "host", "=", "conf", ".", "GetString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "writer", ".", "username", "=", "conf", ".", "GetString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "writer", ".", "password", "=", "conf", ".", "GetString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "writer", ".", "databaseTemplate", "=", "conf", ".", "GetString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "writer", ".", "buffer", "=", "tio", ".", "NewByteStream", "(", "4096", ")", "\n", "writer", ".", "connectionUp", "=", "false", "\n", "writer", ".", "timeBasedDBName", "=", "conf", ".", "GetBool", "(", "\"", "\"", ",", "true", ")", "\n", "writer", ".", "Control", "=", "prod", ".", "Control", "\n", "writer", ".", "logger", "=", "prod", ".", "Logger", "\n\n", "writer", ".", "writeURL", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "writer", ".", "host", ")", "\n", "writer", ".", "queryURL", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "writer", ".", "host", ")", "\n", "writer", ".", "pingURL", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "writer", ".", "host", ")", "\n", "writer", ".", "separator", "=", "'?'", "\n\n", "if", "writer", ".", "username", "!=", "\"", "\"", "{", "credentials", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "url", ".", "QueryEscape", "(", "writer", ".", "username", ")", ",", "url", ".", "QueryEscape", "(", "writer", ".", "password", ")", ")", "\n", "writer", ".", "writeURL", "+=", "credentials", "\n", "writer", ".", "queryURL", "+=", "credentials", "\n", "writer", ".", "separator", "=", "'&'", "\n", "}", "\n\n", "writer", ".", "writeURL", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "writer", ".", "writeURL", ",", "writer", ".", "separator", ")", "\n", "return", "conf", ".", "Errors", ".", "OrNil", "(", ")", "\n", "}" ]
// Configure sets the database connection values
[ "Configure", "sets", "the", "database", "connection", "values" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/InfluxDBWriter10.go#L49-L74
train
trivago/gollum
producer/awsS3.go
Produce
func (prod *AwsS3) Produce(workers *sync.WaitGroup) { prod.initS3Client() prod.AddMainWorker(workers) prod.TickerMessageControlLoop(prod.writeMessage, prod.BatchConfig.BatchTimeout, prod.writeBatchOnTimeOut) }
go
func (prod *AwsS3) Produce(workers *sync.WaitGroup) { prod.initS3Client() prod.AddMainWorker(workers) prod.TickerMessageControlLoop(prod.writeMessage, prod.BatchConfig.BatchTimeout, prod.writeBatchOnTimeOut) }
[ "func", "(", "prod", "*", "AwsS3", ")", "Produce", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "prod", ".", "initS3Client", "(", ")", "\n\n", "prod", ".", "AddMainWorker", "(", "workers", ")", "\n", "prod", ".", "TickerMessageControlLoop", "(", "prod", ".", "writeMessage", ",", "prod", ".", "BatchConfig", ".", "BatchTimeout", ",", "prod", ".", "writeBatchOnTimeOut", ")", "\n", "}" ]
// Produce writes to a buffer that is send to S3 as a multipart upload.
[ "Produce", "writes", "to", "a", "buffer", "that", "is", "send", "to", "S3", "as", "a", "multipart", "upload", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsS3.go#L118-L123
train
trivago/gollum
core/pluginstructtag.go
GetBool
func (tag PluginStructTag) GetBool() bool { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet || tagValue == "" { return false } value, err := strconv.ParseBool(tagValue) if err != nil { panic(err) } return value }
go
func (tag PluginStructTag) GetBool() bool { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet || tagValue == "" { return false } value, err := strconv.ParseBool(tagValue) if err != nil { panic(err) } return value }
[ "func", "(", "tag", "PluginStructTag", ")", "GetBool", "(", ")", "bool", "{", "tagValue", ",", "tagSet", ":=", "reflect", ".", "StructTag", "(", "tag", ")", ".", "Lookup", "(", "PluginStructTagDefault", ")", "\n", "if", "!", "tagSet", "||", "tagValue", "==", "\"", "\"", "{", "return", "false", "\n", "}", "\n", "value", ",", "err", ":=", "strconv", ".", "ParseBool", "(", "tagValue", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "value", "\n", "}" ]
// GetBool returns the default boolean value for an auto configured field. // When not set, false is returned.
[ "GetBool", "returns", "the", "default", "boolean", "value", "for", "an", "auto", "configured", "field", ".", "When", "not", "set", "false", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L38-L48
train
trivago/gollum
core/pluginstructtag.go
GetInt
func (tag PluginStructTag) GetInt() int64 { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet || len(tagValue) == 0 { return 0 } value, err := tstrings.AtoI64(tagValue) if err != nil { panic(err) } return value }
go
func (tag PluginStructTag) GetInt() int64 { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet || len(tagValue) == 0 { return 0 } value, err := tstrings.AtoI64(tagValue) if err != nil { panic(err) } return value }
[ "func", "(", "tag", "PluginStructTag", ")", "GetInt", "(", ")", "int64", "{", "tagValue", ",", "tagSet", ":=", "reflect", ".", "StructTag", "(", "tag", ")", ".", "Lookup", "(", "PluginStructTagDefault", ")", "\n", "if", "!", "tagSet", "||", "len", "(", "tagValue", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "value", ",", "err", ":=", "tstrings", ".", "AtoI64", "(", "tagValue", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "value", "\n", "}" ]
// GetInt returns the default integer value for an auto configured field. // When not set, 0 is returned. Metrics are not applied to this value.
[ "GetInt", "returns", "the", "default", "integer", "value", "for", "an", "auto", "configured", "field", ".", "When", "not", "set", "0", "is", "returned", ".", "Metrics", "are", "not", "applied", "to", "this", "value", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L52-L63
train
trivago/gollum
core/pluginstructtag.go
GetUint
func (tag PluginStructTag) GetUint() uint64 { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet || len(tagValue) == 0 { return 0 } value, err := tstrings.AtoU64(tagValue) if err != nil { panic(err) } return value }
go
func (tag PluginStructTag) GetUint() uint64 { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet || len(tagValue) == 0 { return 0 } value, err := tstrings.AtoU64(tagValue) if err != nil { panic(err) } return value }
[ "func", "(", "tag", "PluginStructTag", ")", "GetUint", "(", ")", "uint64", "{", "tagValue", ",", "tagSet", ":=", "reflect", ".", "StructTag", "(", "tag", ")", ".", "Lookup", "(", "PluginStructTagDefault", ")", "\n", "if", "!", "tagSet", "||", "len", "(", "tagValue", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "value", ",", "err", ":=", "tstrings", ".", "AtoU64", "(", "tagValue", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "value", "\n", "}" ]
// GetUint returns the default unsigned integer value for an auto configured // field. When not set, 0 is returned. Metrics are not applied to this value.
[ "GetUint", "returns", "the", "default", "unsigned", "integer", "value", "for", "an", "auto", "configured", "field", ".", "When", "not", "set", "0", "is", "returned", ".", "Metrics", "are", "not", "applied", "to", "this", "value", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L67-L78
train
trivago/gollum
core/pluginstructtag.go
GetString
func (tag PluginStructTag) GetString() string { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet { return "" } return tstrings.Unescape(tagValue) }
go
func (tag PluginStructTag) GetString() string { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet { return "" } return tstrings.Unescape(tagValue) }
[ "func", "(", "tag", "PluginStructTag", ")", "GetString", "(", ")", "string", "{", "tagValue", ",", "tagSet", ":=", "reflect", ".", "StructTag", "(", "tag", ")", ".", "Lookup", "(", "PluginStructTagDefault", ")", "\n", "if", "!", "tagSet", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "tstrings", ".", "Unescape", "(", "tagValue", ")", "\n", "}" ]
// GetString returns the default string value for an auto configured field. // When not set, "" is returned.
[ "GetString", "returns", "the", "default", "string", "value", "for", "an", "auto", "configured", "field", ".", "When", "not", "set", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L82-L88
train
trivago/gollum
core/pluginstructtag.go
GetStream
func (tag PluginStructTag) GetStream() MessageStreamID { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet { return InvalidStreamID } return GetStreamID(tagValue) }
go
func (tag PluginStructTag) GetStream() MessageStreamID { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet { return InvalidStreamID } return GetStreamID(tagValue) }
[ "func", "(", "tag", "PluginStructTag", ")", "GetStream", "(", ")", "MessageStreamID", "{", "tagValue", ",", "tagSet", ":=", "reflect", ".", "StructTag", "(", "tag", ")", ".", "Lookup", "(", "PluginStructTagDefault", ")", "\n", "if", "!", "tagSet", "{", "return", "InvalidStreamID", "\n", "}", "\n", "return", "GetStreamID", "(", "tagValue", ")", "\n", "}" ]
// GetStream returns the default message stream value for an auto configured // field. When not set, InvalidStream is returned.
[ "GetStream", "returns", "the", "default", "message", "stream", "value", "for", "an", "auto", "configured", "field", ".", "When", "not", "set", "InvalidStream", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L92-L98
train
trivago/gollum
core/pluginstructtag.go
GetStringArray
func (tag PluginStructTag) GetStringArray() []string { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet { return []string{} } return strings.Split(tagValue, ",") }
go
func (tag PluginStructTag) GetStringArray() []string { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet { return []string{} } return strings.Split(tagValue, ",") }
[ "func", "(", "tag", "PluginStructTag", ")", "GetStringArray", "(", ")", "[", "]", "string", "{", "tagValue", ",", "tagSet", ":=", "reflect", ".", "StructTag", "(", "tag", ")", ".", "Lookup", "(", "PluginStructTagDefault", ")", "\n", "if", "!", "tagSet", "{", "return", "[", "]", "string", "{", "}", "\n", "}", "\n", "return", "strings", ".", "Split", "(", "tagValue", ",", "\"", "\"", ")", "\n", "}" ]
// GetStringArray returns the default string array value for an auto configured // field. When not set an empty array is returned.
[ "GetStringArray", "returns", "the", "default", "string", "array", "value", "for", "an", "auto", "configured", "field", ".", "When", "not", "set", "an", "empty", "array", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L102-L108
train
trivago/gollum
core/pluginstructtag.go
GetByteArray
func (tag PluginStructTag) GetByteArray() []byte { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet { return []byte{} } return []byte(tagValue) }
go
func (tag PluginStructTag) GetByteArray() []byte { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagDefault) if !tagSet { return []byte{} } return []byte(tagValue) }
[ "func", "(", "tag", "PluginStructTag", ")", "GetByteArray", "(", ")", "[", "]", "byte", "{", "tagValue", ",", "tagSet", ":=", "reflect", ".", "StructTag", "(", "tag", ")", ".", "Lookup", "(", "PluginStructTagDefault", ")", "\n", "if", "!", "tagSet", "{", "return", "[", "]", "byte", "{", "}", "\n", "}", "\n", "return", "[", "]", "byte", "(", "tagValue", ")", "\n", "}" ]
// GetByteArray returns the default byte array value for an auto configured // field. When not set an empty array is returned.
[ "GetByteArray", "returns", "the", "default", "byte", "array", "value", "for", "an", "auto", "configured", "field", ".", "When", "not", "set", "an", "empty", "array", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L112-L118
train
trivago/gollum
core/pluginstructtag.go
GetStreamArray
func (tag PluginStructTag) GetStreamArray() []MessageStreamID { streamNames := tag.GetStringArray() streamIDs := make([]MessageStreamID, 0, len(streamNames)) for _, name := range streamNames { streamIDs = append(streamIDs, GetStreamID(strings.TrimSpace(name))) } return streamIDs }
go
func (tag PluginStructTag) GetStreamArray() []MessageStreamID { streamNames := tag.GetStringArray() streamIDs := make([]MessageStreamID, 0, len(streamNames)) for _, name := range streamNames { streamIDs = append(streamIDs, GetStreamID(strings.TrimSpace(name))) } return streamIDs }
[ "func", "(", "tag", "PluginStructTag", ")", "GetStreamArray", "(", ")", "[", "]", "MessageStreamID", "{", "streamNames", ":=", "tag", ".", "GetStringArray", "(", ")", "\n", "streamIDs", ":=", "make", "(", "[", "]", "MessageStreamID", ",", "0", ",", "len", "(", "streamNames", ")", ")", "\n", "for", "_", ",", "name", ":=", "range", "streamNames", "{", "streamIDs", "=", "append", "(", "streamIDs", ",", "GetStreamID", "(", "strings", ".", "TrimSpace", "(", "name", ")", ")", ")", "\n", "}", "\n\n", "return", "streamIDs", "\n", "}" ]
// GetStreamArray returns the default message stream array value for an auto // configured field. When not set an empty array is returned.
[ "GetStreamArray", "returns", "the", "default", "message", "stream", "array", "value", "for", "an", "auto", "configured", "field", ".", "When", "not", "set", "an", "empty", "array", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L122-L130
train
trivago/gollum
core/pluginstructtag.go
GetMetricScale
func (tag PluginStructTag) GetMetricScale() int64 { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagMetric) if !tagSet { return 1 } return metricScale[strings.ToLower(tagValue)] }
go
func (tag PluginStructTag) GetMetricScale() int64 { tagValue, tagSet := reflect.StructTag(tag).Lookup(PluginStructTagMetric) if !tagSet { return 1 } return metricScale[strings.ToLower(tagValue)] }
[ "func", "(", "tag", "PluginStructTag", ")", "GetMetricScale", "(", ")", "int64", "{", "tagValue", ",", "tagSet", ":=", "reflect", ".", "StructTag", "(", "tag", ")", ".", "Lookup", "(", "PluginStructTagMetric", ")", "\n", "if", "!", "tagSet", "{", "return", "1", "\n", "}", "\n\n", "return", "metricScale", "[", "strings", ".", "ToLower", "(", "tagValue", ")", "]", "\n", "}" ]
// GetMetricScale returns the scale as defined by the "metric" tag as a number.
[ "GetMetricScale", "returns", "the", "scale", "as", "defined", "by", "the", "metric", "tag", "as", "a", "number", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginstructtag.go#L133-L140
train
trivago/gollum
format/groktojson.go
applyGrok
func (format *GrokToJSON) applyGrok(content string) (map[string]string, error) { for _, exp := range format.exp { values := exp.ParseString(content) if len(values) > 0 { return values, nil } } format.Logger.Warningf("Message does not match any pattern: %s", content) return nil, fmt.Errorf("grok parsing error") }
go
func (format *GrokToJSON) applyGrok(content string) (map[string]string, error) { for _, exp := range format.exp { values := exp.ParseString(content) if len(values) > 0 { return values, nil } } format.Logger.Warningf("Message does not match any pattern: %s", content) return nil, fmt.Errorf("grok parsing error") }
[ "func", "(", "format", "*", "GrokToJSON", ")", "applyGrok", "(", "content", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "for", "_", ",", "exp", ":=", "range", "format", ".", "exp", "{", "values", ":=", "exp", ".", "ParseString", "(", "content", ")", "\n", "if", "len", "(", "values", ")", ">", "0", "{", "return", "values", ",", "nil", "\n", "}", "\n", "}", "\n", "format", ".", "Logger", ".", "Warningf", "(", "\"", "\"", ",", "content", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// grok iterates over all defined patterns and parses the content based on the first match. // It returns a map of the defined values.
[ "grok", "iterates", "over", "all", "defined", "patterns", "and", "parses", "the", "content", "based", "on", "the", "first", "match", ".", "It", "returns", "a", "map", "of", "the", "defined", "values", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/format/groktojson.go#L130-L139
train
trivago/gollum
consumer/console.go
Enqueue
func (cons *Console) Enqueue(data []byte) { if cons.hasToSetMetadata { metaData := core.Metadata{} metaData.SetValue("pipe", []byte(cons.pipeName)) cons.EnqueueWithMetadata(data, metaData) } else { cons.SimpleConsumer.Enqueue(data) } }
go
func (cons *Console) Enqueue(data []byte) { if cons.hasToSetMetadata { metaData := core.Metadata{} metaData.SetValue("pipe", []byte(cons.pipeName)) cons.EnqueueWithMetadata(data, metaData) } else { cons.SimpleConsumer.Enqueue(data) } }
[ "func", "(", "cons", "*", "Console", ")", "Enqueue", "(", "data", "[", "]", "byte", ")", "{", "if", "cons", ".", "hasToSetMetadata", "{", "metaData", ":=", "core", ".", "Metadata", "{", "}", "\n", "metaData", ".", "SetValue", "(", "\"", "\"", ",", "[", "]", "byte", "(", "cons", ".", "pipeName", ")", ")", "\n\n", "cons", ".", "EnqueueWithMetadata", "(", "data", ",", "metaData", ")", "\n", "}", "else", "{", "cons", ".", "SimpleConsumer", ".", "Enqueue", "(", "data", ")", "\n", "}", "\n", "}" ]
// Enqueue creates a new message
[ "Enqueue", "creates", "a", "new", "message" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/consumer/console.go#L96-L105
train
trivago/gollum
docs/generator/tree.go
NewTree
func NewTree(rootAstNode ast.Node) *TreeNode { treeCursor := treeCursor{} // Stub root treeCursor.root = &TreeNode{ AstNode: nil, Parent: nil, Children: []*TreeNode{}, } treeCursor.current = treeCursor.root treeCursor.currentDepth = 0 // Populate the tree ast.Inspect(rootAstNode, treeCursor.insert) // Return the actual root return treeCursor.root.Children[0] }
go
func NewTree(rootAstNode ast.Node) *TreeNode { treeCursor := treeCursor{} // Stub root treeCursor.root = &TreeNode{ AstNode: nil, Parent: nil, Children: []*TreeNode{}, } treeCursor.current = treeCursor.root treeCursor.currentDepth = 0 // Populate the tree ast.Inspect(rootAstNode, treeCursor.insert) // Return the actual root return treeCursor.root.Children[0] }
[ "func", "NewTree", "(", "rootAstNode", "ast", ".", "Node", ")", "*", "TreeNode", "{", "treeCursor", ":=", "treeCursor", "{", "}", "\n\n", "// Stub root", "treeCursor", ".", "root", "=", "&", "TreeNode", "{", "AstNode", ":", "nil", ",", "Parent", ":", "nil", ",", "Children", ":", "[", "]", "*", "TreeNode", "{", "}", ",", "}", "\n", "treeCursor", ".", "current", "=", "treeCursor", ".", "root", "\n", "treeCursor", ".", "currentDepth", "=", "0", "\n\n", "// Populate the tree", "ast", ".", "Inspect", "(", "rootAstNode", ",", "treeCursor", ".", "insert", ")", "\n\n", "// Return the actual root", "return", "treeCursor", ".", "root", ".", "Children", "[", "0", "]", "\n", "}" ]
// NewTree creates a new tree of TreeNodes from the contents of the Go AST rooted at rootAstNode. // Returns a pointer to the root TreeNode.
[ "NewTree", "creates", "a", "new", "tree", "of", "TreeNodes", "from", "the", "contents", "of", "the", "Go", "AST", "rooted", "at", "rootAstNode", ".", "Returns", "a", "pointer", "to", "the", "root", "TreeNode", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/tree.go#L59-L76
train
trivago/gollum
docs/generator/tree.go
Search
func (treeNode *TreeNode) Search(patternNode PatternNode) []*TreeNode { results := []*TreeNode{} // Current node if treeNode.compare(patternNode) { results = append(results, treeNode) } // Current node's children for _, child := range treeNode.Children { for _, subResult := range child.Search(patternNode) { results = append(results, subResult) } } return results }
go
func (treeNode *TreeNode) Search(patternNode PatternNode) []*TreeNode { results := []*TreeNode{} // Current node if treeNode.compare(patternNode) { results = append(results, treeNode) } // Current node's children for _, child := range treeNode.Children { for _, subResult := range child.Search(patternNode) { results = append(results, subResult) } } return results }
[ "func", "(", "treeNode", "*", "TreeNode", ")", "Search", "(", "patternNode", "PatternNode", ")", "[", "]", "*", "TreeNode", "{", "results", ":=", "[", "]", "*", "TreeNode", "{", "}", "\n\n", "// Current node", "if", "treeNode", ".", "compare", "(", "patternNode", ")", "{", "results", "=", "append", "(", "results", ",", "treeNode", ")", "\n", "}", "\n\n", "// Current node's children", "for", "_", ",", "child", ":=", "range", "treeNode", ".", "Children", "{", "for", "_", ",", "subResult", ":=", "range", "child", ".", "Search", "(", "patternNode", ")", "{", "results", "=", "append", "(", "results", ",", "subResult", ")", "\n", "}", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// Search iterates recursively through all subtrees of TreeNode and compares them to // the pattern three rooted at patternNode. It returns a flat list containing the // matching subtrees' roots.
[ "Search", "iterates", "recursively", "through", "all", "subtrees", "of", "TreeNode", "and", "compares", "them", "to", "the", "pattern", "three", "rooted", "at", "patternNode", ".", "It", "returns", "a", "flat", "list", "containing", "the", "matching", "subtrees", "roots", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/tree.go#L107-L123
train
trivago/gollum
docs/generator/tree.go
Dump
func (treeNode *TreeNode) Dump() { fmt.Printf("%s<%p>%q\n", strings.Repeat(" ", 4*treeNode.Depth), treeNode, treeNode.astNodeDump()) for _, child := range treeNode.Children { child.Dump() } }
go
func (treeNode *TreeNode) Dump() { fmt.Printf("%s<%p>%q\n", strings.Repeat(" ", 4*treeNode.Depth), treeNode, treeNode.astNodeDump()) for _, child := range treeNode.Children { child.Dump() } }
[ "func", "(", "treeNode", "*", "TreeNode", ")", "Dump", "(", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "strings", ".", "Repeat", "(", "\"", "\"", ",", "4", "*", "treeNode", ".", "Depth", ")", ",", "treeNode", ",", "treeNode", ".", "astNodeDump", "(", ")", ")", "\n", "for", "_", ",", "child", ":=", "range", "treeNode", ".", "Children", "{", "child", ".", "Dump", "(", ")", "\n", "}", "\n", "}" ]
// Dump prints a dumpString of the tree rooted at `treeNode` to stdout
[ "Dump", "prints", "a", "dumpString", "of", "the", "tree", "rooted", "at", "treeNode", "to", "stdout" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/tree.go#L168-L173
train
trivago/gollum
consumer/profiler.go
Consume
func (cons *Profiler) Consume(workers *sync.WaitGroup) { cons.AddMainWorker(workers) go tgo.WithRecoverShutdown(cons.profile) cons.ControlLoop() }
go
func (cons *Profiler) Consume(workers *sync.WaitGroup) { cons.AddMainWorker(workers) go tgo.WithRecoverShutdown(cons.profile) cons.ControlLoop() }
[ "func", "(", "cons", "*", "Profiler", ")", "Consume", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "cons", ".", "AddMainWorker", "(", "workers", ")", "\n\n", "go", "tgo", ".", "WithRecoverShutdown", "(", "cons", ".", "profile", ")", "\n", "cons", ".", "ControlLoop", "(", ")", "\n", "}" ]
// Consume starts a profile run and exits gollum when done
[ "Consume", "starts", "a", "profile", "run", "and", "exits", "gollum", "when", "done" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/consumer/profiler.go#L230-L235
train
trivago/gollum
producer/file/batchedFileWriter.go
IsAccessible
func (w *BatchedFileWriter) IsAccessible() bool { _, err := w.getStats() return err == nil }
go
func (w *BatchedFileWriter) IsAccessible() bool { _, err := w.getStats() return err == nil }
[ "func", "(", "w", "*", "BatchedFileWriter", ")", "IsAccessible", "(", ")", "bool", "{", "_", ",", "err", ":=", "w", ".", "getStats", "(", ")", "\n", "return", "err", "==", "nil", "\n", "}" ]
// IsAccessible is part of the BatchedWriter interface and check if the writer can access his file
[ "IsAccessible", "is", "part", "of", "the", "BatchedWriter", "interface", "and", "check", "if", "the", "writer", "can", "access", "his", "file" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/file/batchedFileWriter.go#L66-L69
train
trivago/gollum
contrib/native/pcap/pcapsession.go
newPcapSession
func newPcapSession(client string, logger logrus.FieldLogger) *pcapSession { return &pcapSession{ client: client, logger: logger, } }
go
func newPcapSession(client string, logger logrus.FieldLogger) *pcapSession { return &pcapSession{ client: client, logger: logger, } }
[ "func", "newPcapSession", "(", "client", "string", ",", "logger", "logrus", ".", "FieldLogger", ")", "*", "pcapSession", "{", "return", "&", "pcapSession", "{", "client", ":", "client", ",", "logger", ":", "logger", ",", "}", "\n", "}" ]
// create a new TCP session buffer
[ "create", "a", "new", "TCP", "session", "buffer" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L57-L62
train
trivago/gollum
contrib/native/pcap/pcapsession.go
findPacketSlot
func findPacketSlot(seq uint32, list packetList) (int, bool) { offset := 0 partLen := len(list) for partLen > 1 { median := partLen / 2 TCPHeader, _ := tcpFromPcap(list[offset+median]) switch { case seq < TCPHeader.Seq: partLen = median case seq > TCPHeader.Seq: offset += median + 1 partLen -= median + 1 default: return offset, true // ### return, duplicate ### } } if partLen == 0 { return offset, false // ### return, out of range ### } TCPHeader, _ := tcpFromPcap(list[offset]) if seq > TCPHeader.Seq { return offset + 1, false } return offset, seq == TCPHeader.Seq // ### return, duplicate ### }
go
func findPacketSlot(seq uint32, list packetList) (int, bool) { offset := 0 partLen := len(list) for partLen > 1 { median := partLen / 2 TCPHeader, _ := tcpFromPcap(list[offset+median]) switch { case seq < TCPHeader.Seq: partLen = median case seq > TCPHeader.Seq: offset += median + 1 partLen -= median + 1 default: return offset, true // ### return, duplicate ### } } if partLen == 0 { return offset, false // ### return, out of range ### } TCPHeader, _ := tcpFromPcap(list[offset]) if seq > TCPHeader.Seq { return offset + 1, false } return offset, seq == TCPHeader.Seq // ### return, duplicate ### }
[ "func", "findPacketSlot", "(", "seq", "uint32", ",", "list", "packetList", ")", "(", "int", ",", "bool", ")", "{", "offset", ":=", "0", "\n", "partLen", ":=", "len", "(", "list", ")", "\n\n", "for", "partLen", ">", "1", "{", "median", ":=", "partLen", "/", "2", "\n", "TCPHeader", ",", "_", ":=", "tcpFromPcap", "(", "list", "[", "offset", "+", "median", "]", ")", "\n", "switch", "{", "case", "seq", "<", "TCPHeader", ".", "Seq", ":", "partLen", "=", "median", "\n", "case", "seq", ">", "TCPHeader", ".", "Seq", ":", "offset", "+=", "median", "+", "1", "\n", "partLen", "-=", "median", "+", "1", "\n", "default", ":", "return", "offset", ",", "true", "// ### return, duplicate ###", "\n", "}", "\n", "}", "\n\n", "if", "partLen", "==", "0", "{", "return", "offset", ",", "false", "// ### return, out of range ###", "\n", "}", "\n\n", "TCPHeader", ",", "_", ":=", "tcpFromPcap", "(", "list", "[", "offset", "]", ")", "\n", "if", "seq", ">", "TCPHeader", ".", "Seq", "{", "return", "offset", "+", "1", ",", "false", "\n", "}", "\n\n", "return", "offset", ",", "seq", "==", "TCPHeader", ".", "Seq", "// ### return, duplicate ###", "\n", "}" ]
// binary search for an insertion point in the packet list
[ "binary", "search", "for", "an", "insertion", "point", "in", "the", "packet", "list" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L97-L125
train
trivago/gollum
contrib/native/pcap/pcapsession.go
insert
func (list packetList) insert(newPkt *pcap.Packet) packetList { if len(list) == 0 { return packetList{newPkt} } // 32-Bit integer overflow handling (stable for 65k blocks). // If the smallest (leftmost) number in the stored packages is much smaller // or much larger than the incoming number there is an overflow TCPHeader, _ := tcpFromPcap(newPkt) newPktSeq := TCPHeader.Seq frontTCPHeader, _ := tcpFromPcap(list[0]) backTCPHeader, _ := tcpFromPcap(list[len(list)-1]) if newPktSeq < seqLow && frontTCPHeader.Seq > seqHigh { // Overflow: add low value segment packet for i, pkt := range list { TCPHeader, _ = tcpFromPcap(pkt) if TCPHeader.Seq > seqHigh { continue // skip high value segment } if newPktSeq < TCPHeader.Seq { return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ### } if newPktSeq == TCPHeader.Seq { list[i] = newPkt return list // ### return, replaced ### } } } else if newPktSeq > seqHigh && backTCPHeader.Seq < seqLow { // Overflow: add high value segment packet for i, pkt := range list { TCPHeader, _ = tcpFromPcap(pkt) if newPktSeq < TCPHeader.Seq || TCPHeader.Seq < seqLow { return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ### } if newPktSeq == TCPHeader.Seq { list[i] = newPkt return list // ### return, replaced ### } } } else { // Large package insert (binary search) if len(list) > 10 { i, duplicate := findPacketSlot(newPktSeq, list) switch { case duplicate: list[i] = newPkt return list // ### return, replaced ### case i < 0: return append(packetList{newPkt}, list...) // ### return, prepend ### case i < len(list): return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ### } } else { // Small package insert (linear Search) for i, pkt := range list { TCPHeader, _ = tcpFromPcap(pkt) if newPktSeq < TCPHeader.Seq { return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ### } if newPktSeq == TCPHeader.Seq { list[i] = newPkt return list // ### return, replaced ### } } } } return append(list, newPkt) }
go
func (list packetList) insert(newPkt *pcap.Packet) packetList { if len(list) == 0 { return packetList{newPkt} } // 32-Bit integer overflow handling (stable for 65k blocks). // If the smallest (leftmost) number in the stored packages is much smaller // or much larger than the incoming number there is an overflow TCPHeader, _ := tcpFromPcap(newPkt) newPktSeq := TCPHeader.Seq frontTCPHeader, _ := tcpFromPcap(list[0]) backTCPHeader, _ := tcpFromPcap(list[len(list)-1]) if newPktSeq < seqLow && frontTCPHeader.Seq > seqHigh { // Overflow: add low value segment packet for i, pkt := range list { TCPHeader, _ = tcpFromPcap(pkt) if TCPHeader.Seq > seqHigh { continue // skip high value segment } if newPktSeq < TCPHeader.Seq { return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ### } if newPktSeq == TCPHeader.Seq { list[i] = newPkt return list // ### return, replaced ### } } } else if newPktSeq > seqHigh && backTCPHeader.Seq < seqLow { // Overflow: add high value segment packet for i, pkt := range list { TCPHeader, _ = tcpFromPcap(pkt) if newPktSeq < TCPHeader.Seq || TCPHeader.Seq < seqLow { return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ### } if newPktSeq == TCPHeader.Seq { list[i] = newPkt return list // ### return, replaced ### } } } else { // Large package insert (binary search) if len(list) > 10 { i, duplicate := findPacketSlot(newPktSeq, list) switch { case duplicate: list[i] = newPkt return list // ### return, replaced ### case i < 0: return append(packetList{newPkt}, list...) // ### return, prepend ### case i < len(list): return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ### } } else { // Small package insert (linear Search) for i, pkt := range list { TCPHeader, _ = tcpFromPcap(pkt) if newPktSeq < TCPHeader.Seq { return append(list[:i], append(packetList{newPkt}, list[i:]...)...) // ### return insert ### } if newPktSeq == TCPHeader.Seq { list[i] = newPkt return list // ### return, replaced ### } } } } return append(list, newPkt) }
[ "func", "(", "list", "packetList", ")", "insert", "(", "newPkt", "*", "pcap", ".", "Packet", ")", "packetList", "{", "if", "len", "(", "list", ")", "==", "0", "{", "return", "packetList", "{", "newPkt", "}", "\n", "}", "\n\n", "// 32-Bit integer overflow handling (stable for 65k blocks).", "// If the smallest (leftmost) number in the stored packages is much smaller", "// or much larger than the incoming number there is an overflow", "TCPHeader", ",", "_", ":=", "tcpFromPcap", "(", "newPkt", ")", "\n", "newPktSeq", ":=", "TCPHeader", ".", "Seq", "\n", "frontTCPHeader", ",", "_", ":=", "tcpFromPcap", "(", "list", "[", "0", "]", ")", "\n", "backTCPHeader", ",", "_", ":=", "tcpFromPcap", "(", "list", "[", "len", "(", "list", ")", "-", "1", "]", ")", "\n\n", "if", "newPktSeq", "<", "seqLow", "&&", "frontTCPHeader", ".", "Seq", ">", "seqHigh", "{", "// Overflow: add low value segment packet", "for", "i", ",", "pkt", ":=", "range", "list", "{", "TCPHeader", ",", "_", "=", "tcpFromPcap", "(", "pkt", ")", "\n", "if", "TCPHeader", ".", "Seq", ">", "seqHigh", "{", "continue", "// skip high value segment", "\n", "}", "\n", "if", "newPktSeq", "<", "TCPHeader", ".", "Seq", "{", "return", "append", "(", "list", "[", ":", "i", "]", ",", "append", "(", "packetList", "{", "newPkt", "}", ",", "list", "[", "i", ":", "]", "...", ")", "...", ")", "// ### return insert ###", "\n", "}", "\n", "if", "newPktSeq", "==", "TCPHeader", ".", "Seq", "{", "list", "[", "i", "]", "=", "newPkt", "\n", "return", "list", "// ### return, replaced ###", "\n", "}", "\n", "}", "\n", "}", "else", "if", "newPktSeq", ">", "seqHigh", "&&", "backTCPHeader", ".", "Seq", "<", "seqLow", "{", "// Overflow: add high value segment packet", "for", "i", ",", "pkt", ":=", "range", "list", "{", "TCPHeader", ",", "_", "=", "tcpFromPcap", "(", "pkt", ")", "\n", "if", "newPktSeq", "<", "TCPHeader", ".", "Seq", "||", "TCPHeader", ".", "Seq", "<", "seqLow", "{", "return", "append", "(", "list", "[", ":", "i", "]", ",", "append", "(", "packetList", "{", "newPkt", "}", ",", "list", "[", "i", ":", "]", "...", ")", "...", ")", "// ### return insert ###", "\n", "}", "\n", "if", "newPktSeq", "==", "TCPHeader", ".", "Seq", "{", "list", "[", "i", "]", "=", "newPkt", "\n", "return", "list", "// ### return, replaced ###", "\n", "}", "\n", "}", "\n", "}", "else", "{", "// Large package insert (binary search)", "if", "len", "(", "list", ")", ">", "10", "{", "i", ",", "duplicate", ":=", "findPacketSlot", "(", "newPktSeq", ",", "list", ")", "\n", "switch", "{", "case", "duplicate", ":", "list", "[", "i", "]", "=", "newPkt", "\n", "return", "list", "// ### return, replaced ###", "\n", "case", "i", "<", "0", ":", "return", "append", "(", "packetList", "{", "newPkt", "}", ",", "list", "...", ")", "// ### return, prepend ###", "\n", "case", "i", "<", "len", "(", "list", ")", ":", "return", "append", "(", "list", "[", ":", "i", "]", ",", "append", "(", "packetList", "{", "newPkt", "}", ",", "list", "[", "i", ":", "]", "...", ")", "...", ")", "// ### return insert ###", "\n", "}", "\n", "}", "else", "{", "// Small package insert (linear Search)", "for", "i", ",", "pkt", ":=", "range", "list", "{", "TCPHeader", ",", "_", "=", "tcpFromPcap", "(", "pkt", ")", "\n", "if", "newPktSeq", "<", "TCPHeader", ".", "Seq", "{", "return", "append", "(", "list", "[", ":", "i", "]", ",", "append", "(", "packetList", "{", "newPkt", "}", ",", "list", "[", "i", ":", "]", "...", ")", "...", ")", "// ### return insert ###", "\n", "}", "\n", "if", "newPktSeq", "==", "TCPHeader", ".", "Seq", "{", "list", "[", "i", "]", "=", "newPkt", "\n", "return", "list", "// ### return, replaced ###", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "append", "(", "list", ",", "newPkt", ")", "\n", "}" ]
// insertion sort for new packages by sequence number
[ "insertion", "sort", "for", "new", "packages", "by", "sequence", "number" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L128-L198
train
trivago/gollum
contrib/native/pcap/pcapsession.go
isComplete
func (list packetList) isComplete() (bool, int) { numPackets := len(list) // Trivial cases switch numPackets { case 0: return false, 0 case 1: return true, len(list[0].Payload) case 2: TCPHeader0, _ := tcpFromPcap(list[0]) TCPHeader1, _ := tcpFromPcap(list[1]) size0 := len(list[0].Payload) if TCPHeader0.Seq+uint32(size0) == TCPHeader1.Seq { return true, size0 + len(list[1].Payload) } return false, 0 } // More than 2 packets -> loop TCPHeader, _ := tcpFromPcap(list[0]) payloadSize := len(list[0].Payload) prevSeq := TCPHeader.Seq prevSize := len(list[0].Payload) for i := 1; i < numPackets; i++ { TCPHeader, _ = tcpFromPcap(list[i]) if prevSeq+uint32(prevSize) != TCPHeader.Seq { return false, 0 } prevSeq = TCPHeader.Seq prevSize = len(list[i].Payload) payloadSize += prevSize } return true, payloadSize }
go
func (list packetList) isComplete() (bool, int) { numPackets := len(list) // Trivial cases switch numPackets { case 0: return false, 0 case 1: return true, len(list[0].Payload) case 2: TCPHeader0, _ := tcpFromPcap(list[0]) TCPHeader1, _ := tcpFromPcap(list[1]) size0 := len(list[0].Payload) if TCPHeader0.Seq+uint32(size0) == TCPHeader1.Seq { return true, size0 + len(list[1].Payload) } return false, 0 } // More than 2 packets -> loop TCPHeader, _ := tcpFromPcap(list[0]) payloadSize := len(list[0].Payload) prevSeq := TCPHeader.Seq prevSize := len(list[0].Payload) for i := 1; i < numPackets; i++ { TCPHeader, _ = tcpFromPcap(list[i]) if prevSeq+uint32(prevSize) != TCPHeader.Seq { return false, 0 } prevSeq = TCPHeader.Seq prevSize = len(list[i].Payload) payloadSize += prevSize } return true, payloadSize }
[ "func", "(", "list", "packetList", ")", "isComplete", "(", ")", "(", "bool", ",", "int", ")", "{", "numPackets", ":=", "len", "(", "list", ")", "\n\n", "// Trivial cases", "switch", "numPackets", "{", "case", "0", ":", "return", "false", ",", "0", "\n", "case", "1", ":", "return", "true", ",", "len", "(", "list", "[", "0", "]", ".", "Payload", ")", "\n", "case", "2", ":", "TCPHeader0", ",", "_", ":=", "tcpFromPcap", "(", "list", "[", "0", "]", ")", "\n", "TCPHeader1", ",", "_", ":=", "tcpFromPcap", "(", "list", "[", "1", "]", ")", "\n", "size0", ":=", "len", "(", "list", "[", "0", "]", ".", "Payload", ")", "\n\n", "if", "TCPHeader0", ".", "Seq", "+", "uint32", "(", "size0", ")", "==", "TCPHeader1", ".", "Seq", "{", "return", "true", ",", "size0", "+", "len", "(", "list", "[", "1", "]", ".", "Payload", ")", "\n", "}", "\n\n", "return", "false", ",", "0", "\n", "}", "\n\n", "// More than 2 packets -> loop", "TCPHeader", ",", "_", ":=", "tcpFromPcap", "(", "list", "[", "0", "]", ")", "\n", "payloadSize", ":=", "len", "(", "list", "[", "0", "]", ".", "Payload", ")", "\n", "prevSeq", ":=", "TCPHeader", ".", "Seq", "\n", "prevSize", ":=", "len", "(", "list", "[", "0", "]", ".", "Payload", ")", "\n\n", "for", "i", ":=", "1", ";", "i", "<", "numPackets", ";", "i", "++", "{", "TCPHeader", ",", "_", "=", "tcpFromPcap", "(", "list", "[", "i", "]", ")", "\n", "if", "prevSeq", "+", "uint32", "(", "prevSize", ")", "!=", "TCPHeader", ".", "Seq", "{", "return", "false", ",", "0", "\n", "}", "\n\n", "prevSeq", "=", "TCPHeader", ".", "Seq", "\n", "prevSize", "=", "len", "(", "list", "[", "i", "]", ".", "Payload", ")", "\n", "payloadSize", "+=", "prevSize", "\n", "}", "\n\n", "return", "true", ",", "payloadSize", "\n", "}" ]
// check if all packets have consecutive sequence numbers and calculate the // buffer size required for processing
[ "check", "if", "all", "packets", "have", "consecutive", "sequence", "numbers", "and", "calculate", "the", "buffer", "size", "required", "for", "processing" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L202-L243
train
trivago/gollum
contrib/native/pcap/pcapsession.go
dropPackets
func (session *pcapSession) dropPackets(size int) { chunkSize := 0 for i, pkt := range session.packets { chunkSize += len(pkt.Payload) if chunkSize > size { session.packets = session.packets[i:] } } session.packets = session.packets[:0] }
go
func (session *pcapSession) dropPackets(size int) { chunkSize := 0 for i, pkt := range session.packets { chunkSize += len(pkt.Payload) if chunkSize > size { session.packets = session.packets[i:] } } session.packets = session.packets[:0] }
[ "func", "(", "session", "*", "pcapSession", ")", "dropPackets", "(", "size", "int", ")", "{", "chunkSize", ":=", "0", "\n", "for", "i", ",", "pkt", ":=", "range", "session", ".", "packets", "{", "chunkSize", "+=", "len", "(", "pkt", ".", "Payload", ")", "\n", "if", "chunkSize", ">", "size", "{", "session", ".", "packets", "=", "session", ".", "packets", "[", "i", ":", "]", "\n", "}", "\n", "}", "\n", "session", ".", "packets", "=", "session", ".", "packets", "[", ":", "0", "]", "\n", "}" ]
// remove processed packets from the list.
[ "remove", "processed", "packets", "from", "the", "list", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L255-L264
train
trivago/gollum
contrib/native/pcap/pcapsession.go
addPacket
func (session *pcapSession) addPacket(cons *PcapHTTPConsumer, pkt *pcap.Packet) { if len(pkt.Payload) == 0 { return // ### return, no payload ### } session.packets = session.packets.insert(pkt) if complete, size := session.packets.isComplete(); complete { payload := bytes.NewBuffer(make([]byte, 0, size)) for _, pkt := range session.packets { payload.Write(pkt.Payload) } payloadReader := bufio.NewReader(payload) for { request, err := http.ReadRequest(payloadReader) if err != nil { session.lastError = err return // ### return, invalid request: packets pending? ### } request.Header.Add("X-Timestamp", strconv.FormatInt(time.Now().Unix(), 10)) request.Header.Add("X-Client-Ip", session.client) extPayload := bytes.NewBuffer(nil) if err := request.Write(extPayload); err != nil { if err == io.ErrUnexpectedEOF { session.lastError = err return // ### return, invalid request: packets pending? ### } // Error: ignore this request session.logger.Error("PcapHTTPConsumer request writer: ", err) } else { // Enqueue this request cons.enqueueBuffer(extPayload.Bytes()) } // Remove processed packets from list if payload.Len() == 0 { session.packets = session.packets[:0] return // ### return, processed everything ### } numReadBytes := size - payload.Len() size = payload.Len() session.dropPackets(numReadBytes) } } }
go
func (session *pcapSession) addPacket(cons *PcapHTTPConsumer, pkt *pcap.Packet) { if len(pkt.Payload) == 0 { return // ### return, no payload ### } session.packets = session.packets.insert(pkt) if complete, size := session.packets.isComplete(); complete { payload := bytes.NewBuffer(make([]byte, 0, size)) for _, pkt := range session.packets { payload.Write(pkt.Payload) } payloadReader := bufio.NewReader(payload) for { request, err := http.ReadRequest(payloadReader) if err != nil { session.lastError = err return // ### return, invalid request: packets pending? ### } request.Header.Add("X-Timestamp", strconv.FormatInt(time.Now().Unix(), 10)) request.Header.Add("X-Client-Ip", session.client) extPayload := bytes.NewBuffer(nil) if err := request.Write(extPayload); err != nil { if err == io.ErrUnexpectedEOF { session.lastError = err return // ### return, invalid request: packets pending? ### } // Error: ignore this request session.logger.Error("PcapHTTPConsumer request writer: ", err) } else { // Enqueue this request cons.enqueueBuffer(extPayload.Bytes()) } // Remove processed packets from list if payload.Len() == 0 { session.packets = session.packets[:0] return // ### return, processed everything ### } numReadBytes := size - payload.Len() size = payload.Len() session.dropPackets(numReadBytes) } } }
[ "func", "(", "session", "*", "pcapSession", ")", "addPacket", "(", "cons", "*", "PcapHTTPConsumer", ",", "pkt", "*", "pcap", ".", "Packet", ")", "{", "if", "len", "(", "pkt", ".", "Payload", ")", "==", "0", "{", "return", "// ### return, no payload ###", "\n", "}", "\n\n", "session", ".", "packets", "=", "session", ".", "packets", ".", "insert", "(", "pkt", ")", "\n\n", "if", "complete", ",", "size", ":=", "session", ".", "packets", ".", "isComplete", "(", ")", ";", "complete", "{", "payload", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "size", ")", ")", "\n", "for", "_", ",", "pkt", ":=", "range", "session", ".", "packets", "{", "payload", ".", "Write", "(", "pkt", ".", "Payload", ")", "\n", "}", "\n\n", "payloadReader", ":=", "bufio", ".", "NewReader", "(", "payload", ")", "\n", "for", "{", "request", ",", "err", ":=", "http", ".", "ReadRequest", "(", "payloadReader", ")", "\n", "if", "err", "!=", "nil", "{", "session", ".", "lastError", "=", "err", "\n", "return", "// ### return, invalid request: packets pending? ###", "\n", "}", "\n\n", "request", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ",", "10", ")", ")", "\n", "request", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "session", ".", "client", ")", "\n\n", "extPayload", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "if", "err", ":=", "request", ".", "Write", "(", "extPayload", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "ErrUnexpectedEOF", "{", "session", ".", "lastError", "=", "err", "\n", "return", "// ### return, invalid request: packets pending? ###", "\n", "}", "\n", "// Error: ignore this request", "session", ".", "logger", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "// Enqueue this request", "cons", ".", "enqueueBuffer", "(", "extPayload", ".", "Bytes", "(", ")", ")", "\n", "}", "\n\n", "// Remove processed packets from list", "if", "payload", ".", "Len", "(", ")", "==", "0", "{", "session", ".", "packets", "=", "session", ".", "packets", "[", ":", "0", "]", "\n", "return", "// ### return, processed everything ###", "\n", "}", "\n\n", "numReadBytes", ":=", "size", "-", "payload", ".", "Len", "(", ")", "\n", "size", "=", "payload", ".", "Len", "(", ")", "\n", "session", ".", "dropPackets", "(", "numReadBytes", ")", "\n", "}", "\n", "}", "\n", "}" ]
// add a TCP packet to the session and try to generate a HTTP packet
[ "add", "a", "TCP", "packet", "to", "the", "session", "and", "try", "to", "generate", "a", "HTTP", "packet" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/pcap/pcapsession.go#L267-L315
train
trivago/gollum
core/simpleconsumer.go
Configure
func (cons *SimpleConsumer) Configure(conf PluginConfigReader) { cons.id = conf.GetID() cons.Logger = conf.GetLogger() cons.runState = NewPluginRunState() cons.control = make(chan PluginControl, 1) numRoutines := conf.GetInt("ModulatorRoutines", 0) queueSize := conf.GetInt("ModulatorQueueSize", 1024) if numRoutines > 0 { cons.Logger.Debugf("Using %d modulator routines", numRoutines) cons.modulatorQueue = NewMessageQueue(int(queueSize)) for i := 0; i < int(numRoutines); i++ { go cons.processQueue() } cons.enqueueMessage = cons.parallelEnqueue } else { cons.enqueueMessage = cons.directEnqueue } // Simple health check for the plugin state // Path: "/<plugin_id>/pluginState" cons.AddHealthCheckAt("/pluginState", func() (code int, body string) { if cons.IsActive() { return thealthcheck.StatusOK, fmt.Sprintf("ACTIVE: %s", cons.runState.GetStateString()) } return thealthcheck.StatusServiceUnavailable, fmt.Sprintf("NOT_ACTIVE: %s", cons.runState.GetStateString()) }) }
go
func (cons *SimpleConsumer) Configure(conf PluginConfigReader) { cons.id = conf.GetID() cons.Logger = conf.GetLogger() cons.runState = NewPluginRunState() cons.control = make(chan PluginControl, 1) numRoutines := conf.GetInt("ModulatorRoutines", 0) queueSize := conf.GetInt("ModulatorQueueSize", 1024) if numRoutines > 0 { cons.Logger.Debugf("Using %d modulator routines", numRoutines) cons.modulatorQueue = NewMessageQueue(int(queueSize)) for i := 0; i < int(numRoutines); i++ { go cons.processQueue() } cons.enqueueMessage = cons.parallelEnqueue } else { cons.enqueueMessage = cons.directEnqueue } // Simple health check for the plugin state // Path: "/<plugin_id>/pluginState" cons.AddHealthCheckAt("/pluginState", func() (code int, body string) { if cons.IsActive() { return thealthcheck.StatusOK, fmt.Sprintf("ACTIVE: %s", cons.runState.GetStateString()) } return thealthcheck.StatusServiceUnavailable, fmt.Sprintf("NOT_ACTIVE: %s", cons.runState.GetStateString()) }) }
[ "func", "(", "cons", "*", "SimpleConsumer", ")", "Configure", "(", "conf", "PluginConfigReader", ")", "{", "cons", ".", "id", "=", "conf", ".", "GetID", "(", ")", "\n", "cons", ".", "Logger", "=", "conf", ".", "GetLogger", "(", ")", "\n", "cons", ".", "runState", "=", "NewPluginRunState", "(", ")", "\n", "cons", ".", "control", "=", "make", "(", "chan", "PluginControl", ",", "1", ")", "\n\n", "numRoutines", ":=", "conf", ".", "GetInt", "(", "\"", "\"", ",", "0", ")", "\n", "queueSize", ":=", "conf", ".", "GetInt", "(", "\"", "\"", ",", "1024", ")", "\n\n", "if", "numRoutines", ">", "0", "{", "cons", ".", "Logger", ".", "Debugf", "(", "\"", "\"", ",", "numRoutines", ")", "\n", "cons", ".", "modulatorQueue", "=", "NewMessageQueue", "(", "int", "(", "queueSize", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "numRoutines", ")", ";", "i", "++", "{", "go", "cons", ".", "processQueue", "(", ")", "\n", "}", "\n", "cons", ".", "enqueueMessage", "=", "cons", ".", "parallelEnqueue", "\n", "}", "else", "{", "cons", ".", "enqueueMessage", "=", "cons", ".", "directEnqueue", "\n", "}", "\n\n", "// Simple health check for the plugin state", "// Path: \"/<plugin_id>/pluginState\"", "cons", ".", "AddHealthCheckAt", "(", "\"", "\"", ",", "func", "(", ")", "(", "code", "int", ",", "body", "string", ")", "{", "if", "cons", ".", "IsActive", "(", ")", "{", "return", "thealthcheck", ".", "StatusOK", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cons", ".", "runState", ".", "GetStateString", "(", ")", ")", "\n", "}", "\n", "return", "thealthcheck", ".", "StatusServiceUnavailable", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cons", ".", "runState", ".", "GetStateString", "(", ")", ")", "\n", "}", ")", "\n", "}" ]
// Configure initializes standard consumer values from a plugin config.
[ "Configure", "initializes", "standard", "consumer", "values", "from", "a", "plugin", "config", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleconsumer.go#L77-L106
train
trivago/gollum
core/simpleconsumer.go
EnqueueWithMetadata
func (cons *SimpleConsumer) EnqueueWithMetadata(data []byte, metaData Metadata) { msg := NewMessage(cons, data, metaData, InvalidStreamID) cons.enqueueMessage(msg) }
go
func (cons *SimpleConsumer) EnqueueWithMetadata(data []byte, metaData Metadata) { msg := NewMessage(cons, data, metaData, InvalidStreamID) cons.enqueueMessage(msg) }
[ "func", "(", "cons", "*", "SimpleConsumer", ")", "EnqueueWithMetadata", "(", "data", "[", "]", "byte", ",", "metaData", "Metadata", ")", "{", "msg", ":=", "NewMessage", "(", "cons", ",", "data", ",", "metaData", ",", "InvalidStreamID", ")", "\n", "cons", ".", "enqueueMessage", "(", "msg", ")", "\n", "}" ]
// EnqueueWithMetadata works like EnqueueWithSequence and allows to set meta data directly
[ "EnqueueWithMetadata", "works", "like", "EnqueueWithSequence", "and", "allows", "to", "set", "meta", "data", "directly" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleconsumer.go#L207-L210
train
trivago/gollum
core/simpleconsumer.go
ControlLoop
func (cons *SimpleConsumer) ControlLoop() { cons.setState(PluginStateActive) defer cons.setState(PluginStateDead) defer cons.Logger.Debug("Stopped") for { command := <-cons.control switch command { default: cons.Logger.Debug("Received untracked command") // Do nothing case PluginControlStopConsumer: cons.Logger.Debug("Preparing for stop") cons.setState(PluginStatePrepareStop) if cons.onPrepareStop != nil { if !tgo.ReturnAfter(cons.shutdownTimeout*5, cons.onPrepareStop) { cons.Logger.Error("Timeout during onPrepareStop") } } cons.Logger.Debug("Executing stop command") cons.setState(PluginStateStopping) if cons.onStop != nil { if !tgo.ReturnAfter(cons.shutdownTimeout*5, cons.onStop) { cons.Logger.Errorf("Timeout during onStop") } } if cons.modulatorQueue != nil { close(cons.modulatorQueue) } return // ### return ### case PluginControlRoll: cons.Logger.Debug("Received roll command") if cons.onRoll != nil { cons.onRoll() } } } }
go
func (cons *SimpleConsumer) ControlLoop() { cons.setState(PluginStateActive) defer cons.setState(PluginStateDead) defer cons.Logger.Debug("Stopped") for { command := <-cons.control switch command { default: cons.Logger.Debug("Received untracked command") // Do nothing case PluginControlStopConsumer: cons.Logger.Debug("Preparing for stop") cons.setState(PluginStatePrepareStop) if cons.onPrepareStop != nil { if !tgo.ReturnAfter(cons.shutdownTimeout*5, cons.onPrepareStop) { cons.Logger.Error("Timeout during onPrepareStop") } } cons.Logger.Debug("Executing stop command") cons.setState(PluginStateStopping) if cons.onStop != nil { if !tgo.ReturnAfter(cons.shutdownTimeout*5, cons.onStop) { cons.Logger.Errorf("Timeout during onStop") } } if cons.modulatorQueue != nil { close(cons.modulatorQueue) } return // ### return ### case PluginControlRoll: cons.Logger.Debug("Received roll command") if cons.onRoll != nil { cons.onRoll() } } } }
[ "func", "(", "cons", "*", "SimpleConsumer", ")", "ControlLoop", "(", ")", "{", "cons", ".", "setState", "(", "PluginStateActive", ")", "\n", "defer", "cons", ".", "setState", "(", "PluginStateDead", ")", "\n", "defer", "cons", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "for", "{", "command", ":=", "<-", "cons", ".", "control", "\n", "switch", "command", "{", "default", ":", "cons", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "// Do nothing", "case", "PluginControlStopConsumer", ":", "cons", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "cons", ".", "setState", "(", "PluginStatePrepareStop", ")", "\n\n", "if", "cons", ".", "onPrepareStop", "!=", "nil", "{", "if", "!", "tgo", ".", "ReturnAfter", "(", "cons", ".", "shutdownTimeout", "*", "5", ",", "cons", ".", "onPrepareStop", ")", "{", "cons", ".", "Logger", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "cons", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "cons", ".", "setState", "(", "PluginStateStopping", ")", "\n\n", "if", "cons", ".", "onStop", "!=", "nil", "{", "if", "!", "tgo", ".", "ReturnAfter", "(", "cons", ".", "shutdownTimeout", "*", "5", ",", "cons", ".", "onStop", ")", "{", "cons", ".", "Logger", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "cons", ".", "modulatorQueue", "!=", "nil", "{", "close", "(", "cons", ".", "modulatorQueue", ")", "\n", "}", "\n", "return", "// ### return ###", "\n\n", "case", "PluginControlRoll", ":", "cons", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "if", "cons", ".", "onRoll", "!=", "nil", "{", "cons", ".", "onRoll", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// ControlLoop listens to the control channel and triggers callbacks for these // messages. Upon stop control message doExit will be set to true.
[ "ControlLoop", "listens", "to", "the", "control", "channel", "and", "triggers", "callbacks", "for", "these", "messages", ".", "Upon", "stop", "control", "message", "doExit", "will", "be", "set", "to", "true", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleconsumer.go#L266-L309
train
trivago/gollum
core/simpleconsumer.go
TickerControlLoop
func (cons *SimpleConsumer) TickerControlLoop(interval time.Duration, onTick func()) { cons.setState(PluginStateActive) go cons.tickerLoop(interval, onTick) cons.ControlLoop() }
go
func (cons *SimpleConsumer) TickerControlLoop(interval time.Duration, onTick func()) { cons.setState(PluginStateActive) go cons.tickerLoop(interval, onTick) cons.ControlLoop() }
[ "func", "(", "cons", "*", "SimpleConsumer", ")", "TickerControlLoop", "(", "interval", "time", ".", "Duration", ",", "onTick", "func", "(", ")", ")", "{", "cons", ".", "setState", "(", "PluginStateActive", ")", "\n", "go", "cons", ".", "tickerLoop", "(", "interval", ",", "onTick", ")", "\n", "cons", ".", "ControlLoop", "(", ")", "\n", "}" ]
// TickerControlLoop is like MessageLoop but executes a given function at // every given interval tick, too. Note that the interval is not exact. If the // onTick function takes longer than interval, the next tick will be delayed // until onTick finishes.
[ "TickerControlLoop", "is", "like", "MessageLoop", "but", "executes", "a", "given", "function", "at", "every", "given", "interval", "tick", "too", ".", "Note", "that", "the", "interval", "is", "not", "exact", ".", "If", "the", "onTick", "function", "takes", "longer", "than", "interval", "the", "next", "tick", "will", "be", "delayed", "until", "onTick", "finishes", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simpleconsumer.go#L315-L319
train
trivago/gollum
producer/awsCloudwatchlogs.go
numEvents
func (prod *AwsCloudwatchLogs) numEvents(messages []*core.Message, checkFn ...indexNumFn) int { index := maxBatchEvents for _, fn := range checkFn { result := fn(messages) if result < index { index = result } } return index }
go
func (prod *AwsCloudwatchLogs) numEvents(messages []*core.Message, checkFn ...indexNumFn) int { index := maxBatchEvents for _, fn := range checkFn { result := fn(messages) if result < index { index = result } } return index }
[ "func", "(", "prod", "*", "AwsCloudwatchLogs", ")", "numEvents", "(", "messages", "[", "]", "*", "core", ".", "Message", ",", "checkFn", "...", "indexNumFn", ")", "int", "{", "index", ":=", "maxBatchEvents", "\n", "for", "_", ",", "fn", ":=", "range", "checkFn", "{", "result", ":=", "fn", "(", "messages", ")", "\n", "if", "result", "<", "index", "{", "index", "=", "result", "\n", "}", "\n", "}", "\n", "return", "index", "\n", "}" ]
// Return lowest index based on all check functions // This function assumes that messages are sorted by timestamp in ascending order
[ "Return", "lowest", "index", "based", "on", "all", "check", "functions", "This", "function", "assumes", "that", "messages", "are", "sorted", "by", "timestamp", "in", "ascending", "order" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L112-L121
train
trivago/gollum
producer/awsCloudwatchlogs.go
sizeIndex
func (prod *AwsCloudwatchLogs) sizeIndex(messages []*core.Message) int { size, index := 0, 0 for i, message := range messages { size += len(message.String()) + eventSizeOverhead if size > maxBatchSize { break } index = i + 1 } return index }
go
func (prod *AwsCloudwatchLogs) sizeIndex(messages []*core.Message) int { size, index := 0, 0 for i, message := range messages { size += len(message.String()) + eventSizeOverhead if size > maxBatchSize { break } index = i + 1 } return index }
[ "func", "(", "prod", "*", "AwsCloudwatchLogs", ")", "sizeIndex", "(", "messages", "[", "]", "*", "core", ".", "Message", ")", "int", "{", "size", ",", "index", ":=", "0", ",", "0", "\n", "for", "i", ",", "message", ":=", "range", "messages", "{", "size", "+=", "len", "(", "message", ".", "String", "(", ")", ")", "+", "eventSizeOverhead", "\n", "if", "size", ">", "maxBatchSize", "{", "break", "\n", "}", "\n", "index", "=", "i", "+", "1", "\n", "}", "\n", "return", "index", "\n", "}" ]
// Return lowest index based on message size
[ "Return", "lowest", "index", "based", "on", "message", "size" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L126-L136
train
trivago/gollum
producer/awsCloudwatchlogs.go
timeIndex
func (prod *AwsCloudwatchLogs) timeIndex(messages []*core.Message) (index int) { if len(messages) == 0 { return 0 } firstTimestamp := messages[0].GetCreationTime().Unix() for i, message := range messages { if (message.GetCreationTime().Unix() - firstTimestamp) > int64(maxBatchTimeSpan) { break } index = i + 1 } return index }
go
func (prod *AwsCloudwatchLogs) timeIndex(messages []*core.Message) (index int) { if len(messages) == 0 { return 0 } firstTimestamp := messages[0].GetCreationTime().Unix() for i, message := range messages { if (message.GetCreationTime().Unix() - firstTimestamp) > int64(maxBatchTimeSpan) { break } index = i + 1 } return index }
[ "func", "(", "prod", "*", "AwsCloudwatchLogs", ")", "timeIndex", "(", "messages", "[", "]", "*", "core", ".", "Message", ")", "(", "index", "int", ")", "{", "if", "len", "(", "messages", ")", "==", "0", "{", "return", "0", "\n", "}", "\n", "firstTimestamp", ":=", "messages", "[", "0", "]", ".", "GetCreationTime", "(", ")", ".", "Unix", "(", ")", "\n", "for", "i", ",", "message", ":=", "range", "messages", "{", "if", "(", "message", ".", "GetCreationTime", "(", ")", ".", "Unix", "(", ")", "-", "firstTimestamp", ")", ">", "int64", "(", "maxBatchTimeSpan", ")", "{", "break", "\n", "}", "\n", "index", "=", "i", "+", "1", "\n", "}", "\n", "return", "index", "\n", "}" ]
// Return lowest index based on timespan // This function assumes that messages are sorted by timestamp in ascending order
[ "Return", "lowest", "index", "based", "on", "timespan", "This", "function", "assumes", "that", "messages", "are", "sorted", "by", "timestamp", "in", "ascending", "order" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L140-L152
train
trivago/gollum
producer/awsCloudwatchlogs.go
handleResult
func (prod *AwsCloudwatchLogs) handleResult(resp *cloudwatchlogs.PutLogEventsOutput, result error) { switch err := result.(type) { case awserr.Error: switch err.Code() { case "InvalidSequenceTokenException": prod.Logger.Debugf("invalid sequence token, updating") prod.setToken() case "ResourceNotFoundException": prod.Logger.Debugf("missing group/stream, creating") prod.create() prod.token = nil default: prod.Logger.Errorf("error while sending batch. code: %s message: %q", err.Code(), err.Message()) } case nil: prod.token = resp.NextSequenceToken default: prod.Logger.Errorf("error while sending batch: %q", err) } }
go
func (prod *AwsCloudwatchLogs) handleResult(resp *cloudwatchlogs.PutLogEventsOutput, result error) { switch err := result.(type) { case awserr.Error: switch err.Code() { case "InvalidSequenceTokenException": prod.Logger.Debugf("invalid sequence token, updating") prod.setToken() case "ResourceNotFoundException": prod.Logger.Debugf("missing group/stream, creating") prod.create() prod.token = nil default: prod.Logger.Errorf("error while sending batch. code: %s message: %q", err.Code(), err.Message()) } case nil: prod.token = resp.NextSequenceToken default: prod.Logger.Errorf("error while sending batch: %q", err) } }
[ "func", "(", "prod", "*", "AwsCloudwatchLogs", ")", "handleResult", "(", "resp", "*", "cloudwatchlogs", ".", "PutLogEventsOutput", ",", "result", "error", ")", "{", "switch", "err", ":=", "result", ".", "(", "type", ")", "{", "case", "awserr", ".", "Error", ":", "switch", "err", ".", "Code", "(", ")", "{", "case", "\"", "\"", ":", "prod", ".", "Logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "prod", ".", "setToken", "(", ")", "\n", "case", "\"", "\"", ":", "prod", ".", "Logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "prod", ".", "create", "(", ")", "\n", "prod", ".", "token", "=", "nil", "\n", "default", ":", "prod", ".", "Logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Code", "(", ")", ",", "err", ".", "Message", "(", ")", ")", "\n", "}", "\n", "case", "nil", ":", "prod", ".", "token", "=", "resp", ".", "NextSequenceToken", "\n", "default", ":", "prod", ".", "Logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// When rejectedLogEventsInfo is not empty, app can not // do anything reasonable with rejected logs. Ignore it.
[ "When", "rejectedLogEventsInfo", "is", "not", "empty", "app", "can", "not", "do", "anything", "reasonable", "with", "rejected", "logs", ".", "Ignore", "it", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L184-L203
train
trivago/gollum
producer/awsCloudwatchlogs.go
setToken
func (prod *AwsCloudwatchLogs) setToken() error { params := &cloudwatchlogs.DescribeLogStreamsInput{ LogGroupName: &prod.group, LogStreamNamePrefix: &prod.stream, } return prod.service.DescribeLogStreamsPages(params, func(page *cloudwatchlogs.DescribeLogStreamsOutput, lastPage bool) bool { return !findToken(prod, page) }) }
go
func (prod *AwsCloudwatchLogs) setToken() error { params := &cloudwatchlogs.DescribeLogStreamsInput{ LogGroupName: &prod.group, LogStreamNamePrefix: &prod.stream, } return prod.service.DescribeLogStreamsPages(params, func(page *cloudwatchlogs.DescribeLogStreamsOutput, lastPage bool) bool { return !findToken(prod, page) }) }
[ "func", "(", "prod", "*", "AwsCloudwatchLogs", ")", "setToken", "(", ")", "error", "{", "params", ":=", "&", "cloudwatchlogs", ".", "DescribeLogStreamsInput", "{", "LogGroupName", ":", "&", "prod", ".", "group", ",", "LogStreamNamePrefix", ":", "&", "prod", ".", "stream", ",", "}", "\n\n", "return", "prod", ".", "service", ".", "DescribeLogStreamsPages", "(", "params", ",", "func", "(", "page", "*", "cloudwatchlogs", ".", "DescribeLogStreamsOutput", ",", "lastPage", "bool", ")", "bool", "{", "return", "!", "findToken", "(", "prod", ",", "page", ")", "\n", "}", ")", "\n", "}" ]
// For newly created log streams, token is an empty string.
[ "For", "newly", "created", "log", "streams", "token", "is", "an", "empty", "string", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L240-L250
train
trivago/gollum
producer/awsCloudwatchlogs.go
create
func (prod *AwsCloudwatchLogs) create() error { if err := prod.createGroup(); err != nil { return err } return prod.createStream() }
go
func (prod *AwsCloudwatchLogs) create() error { if err := prod.createGroup(); err != nil { return err } return prod.createStream() }
[ "func", "(", "prod", "*", "AwsCloudwatchLogs", ")", "create", "(", ")", "error", "{", "if", "err", ":=", "prod", ".", "createGroup", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "prod", ".", "createStream", "(", ")", "\n", "}" ]
// Create log group and stream. If an error is returned, PutLogEvents cannot succeed.
[ "Create", "log", "group", "and", "stream", ".", "If", "an", "error", "is", "returned", "PutLogEvents", "cannot", "succeed", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awsCloudwatchlogs.go#L263-L268
train
microcosm-cc/bluemonday
policies.go
UGCPolicy
func UGCPolicy() *Policy { p := NewPolicy() /////////////////////// // Global attributes // /////////////////////// // "class" is not permitted as we are not allowing users to style their own // content p.AllowStandardAttributes() ////////////////////////////// // Global URL format policy // ////////////////////////////// p.AllowStandardURLs() //////////////////////////////// // Declarations and structure // //////////////////////////////// // "xml" "xslt" "DOCTYPE" "html" "head" are not permitted as we are // expecting user generated content to be a fragment of HTML and not a full // document. ////////////////////////// // Sectioning root tags // ////////////////////////// // "article" and "aside" are permitted and takes no attributes p.AllowElements("article", "aside") // "body" is not permitted as we are expecting user generated content to be a fragment // of HTML and not a full document. // "details" is permitted, including the "open" attribute which can either // be blank or the value "open". p.AllowAttrs( "open", ).Matching(regexp.MustCompile(`(?i)^(|open)$`)).OnElements("details") // "fieldset" is not permitted as we are not allowing forms to be created. // "figure" is permitted and takes no attributes p.AllowElements("figure") // "nav" is not permitted as it is assumed that the site (and not the user) // has defined navigation elements // "section" is permitted and takes no attributes p.AllowElements("section") // "summary" is permitted and takes no attributes p.AllowElements("summary") ////////////////////////// // Headings and footers // ////////////////////////// // "footer" is not permitted as we expect user content to be a fragment and // not structural to this extent // "h1" through "h6" are permitted and take no attributes p.AllowElements("h1", "h2", "h3", "h4", "h5", "h6") // "header" is not permitted as we expect user content to be a fragment and // not structural to this extent // "hgroup" is permitted and takes no attributes p.AllowElements("hgroup") ///////////////////////////////////// // Content grouping and separating // ///////////////////////////////////// // "blockquote" is permitted, including the "cite" attribute which must be // a standard URL. p.AllowAttrs("cite").OnElements("blockquote") // "br" "div" "hr" "p" "span" "wbr" are permitted and take no attributes p.AllowElements("br", "div", "hr", "p", "span", "wbr") /////////// // Links // /////////// // "a" is permitted p.AllowAttrs("href").OnElements("a") // "area" is permitted along with the attributes that map image maps work p.AllowAttrs("name").Matching( regexp.MustCompile(`^([\p{L}\p{N}_-]+)$`), ).OnElements("map") p.AllowAttrs("alt").Matching(Paragraph).OnElements("area") p.AllowAttrs("coords").Matching( regexp.MustCompile(`^([0-9]+,)+[0-9]+$`), ).OnElements("area") p.AllowAttrs("href").OnElements("area") p.AllowAttrs("rel").Matching(SpaceSeparatedTokens).OnElements("area") p.AllowAttrs("shape").Matching( regexp.MustCompile(`(?i)^(default|circle|rect|poly)$`), ).OnElements("area") p.AllowAttrs("usemap").Matching( regexp.MustCompile(`(?i)^#[\p{L}\p{N}_-]+$`), ).OnElements("img") // "link" is not permitted ///////////////////// // Phrase elements // ///////////////////// // The following are all inline phrasing elements p.AllowElements("abbr", "acronym", "cite", "code", "dfn", "em", "figcaption", "mark", "s", "samp", "strong", "sub", "sup", "var") // "q" is permitted and "cite" is a URL and handled by URL policies p.AllowAttrs("cite").OnElements("q") // "time" is permitted p.AllowAttrs("datetime").Matching(ISO8601).OnElements("time") //////////////////// // Style elements // //////////////////// // block and inline elements that impart no semantic meaning but style the // document p.AllowElements("b", "i", "pre", "small", "strike", "tt", "u") // "style" is not permitted as we are not yet sanitising CSS and it is an // XSS attack vector ////////////////////// // HTML5 Formatting // ////////////////////// // "bdi" "bdo" are permitted p.AllowAttrs("dir").Matching(Direction).OnElements("bdi", "bdo") // "rp" "rt" "ruby" are permitted p.AllowElements("rp", "rt", "ruby") /////////////////////////// // HTML5 Change tracking // /////////////////////////// // "del" "ins" are permitted p.AllowAttrs("cite").Matching(Paragraph).OnElements("del", "ins") p.AllowAttrs("datetime").Matching(ISO8601).OnElements("del", "ins") /////////// // Lists // /////////// p.AllowLists() //////////// // Tables // //////////// p.AllowTables() /////////// // Forms // /////////// // By and large, forms are not permitted. However there are some form // elements that can be used to present data, and we do permit those // // "button" "fieldset" "input" "keygen" "label" "output" "select" "datalist" // "textarea" "optgroup" "option" are all not permitted // "meter" is permitted p.AllowAttrs( "value", "min", "max", "low", "high", "optimum", ).Matching(Number).OnElements("meter") // "progress" is permitted p.AllowAttrs("value", "max").Matching(Number).OnElements("progress") ////////////////////// // Embedded content // ////////////////////// // Vast majority not permitted // "audio" "canvas" "embed" "iframe" "object" "param" "source" "svg" "track" // "video" are all not permitted p.AllowImages() return p }
go
func UGCPolicy() *Policy { p := NewPolicy() /////////////////////// // Global attributes // /////////////////////// // "class" is not permitted as we are not allowing users to style their own // content p.AllowStandardAttributes() ////////////////////////////// // Global URL format policy // ////////////////////////////// p.AllowStandardURLs() //////////////////////////////// // Declarations and structure // //////////////////////////////// // "xml" "xslt" "DOCTYPE" "html" "head" are not permitted as we are // expecting user generated content to be a fragment of HTML and not a full // document. ////////////////////////// // Sectioning root tags // ////////////////////////// // "article" and "aside" are permitted and takes no attributes p.AllowElements("article", "aside") // "body" is not permitted as we are expecting user generated content to be a fragment // of HTML and not a full document. // "details" is permitted, including the "open" attribute which can either // be blank or the value "open". p.AllowAttrs( "open", ).Matching(regexp.MustCompile(`(?i)^(|open)$`)).OnElements("details") // "fieldset" is not permitted as we are not allowing forms to be created. // "figure" is permitted and takes no attributes p.AllowElements("figure") // "nav" is not permitted as it is assumed that the site (and not the user) // has defined navigation elements // "section" is permitted and takes no attributes p.AllowElements("section") // "summary" is permitted and takes no attributes p.AllowElements("summary") ////////////////////////// // Headings and footers // ////////////////////////// // "footer" is not permitted as we expect user content to be a fragment and // not structural to this extent // "h1" through "h6" are permitted and take no attributes p.AllowElements("h1", "h2", "h3", "h4", "h5", "h6") // "header" is not permitted as we expect user content to be a fragment and // not structural to this extent // "hgroup" is permitted and takes no attributes p.AllowElements("hgroup") ///////////////////////////////////// // Content grouping and separating // ///////////////////////////////////// // "blockquote" is permitted, including the "cite" attribute which must be // a standard URL. p.AllowAttrs("cite").OnElements("blockquote") // "br" "div" "hr" "p" "span" "wbr" are permitted and take no attributes p.AllowElements("br", "div", "hr", "p", "span", "wbr") /////////// // Links // /////////// // "a" is permitted p.AllowAttrs("href").OnElements("a") // "area" is permitted along with the attributes that map image maps work p.AllowAttrs("name").Matching( regexp.MustCompile(`^([\p{L}\p{N}_-]+)$`), ).OnElements("map") p.AllowAttrs("alt").Matching(Paragraph).OnElements("area") p.AllowAttrs("coords").Matching( regexp.MustCompile(`^([0-9]+,)+[0-9]+$`), ).OnElements("area") p.AllowAttrs("href").OnElements("area") p.AllowAttrs("rel").Matching(SpaceSeparatedTokens).OnElements("area") p.AllowAttrs("shape").Matching( regexp.MustCompile(`(?i)^(default|circle|rect|poly)$`), ).OnElements("area") p.AllowAttrs("usemap").Matching( regexp.MustCompile(`(?i)^#[\p{L}\p{N}_-]+$`), ).OnElements("img") // "link" is not permitted ///////////////////// // Phrase elements // ///////////////////// // The following are all inline phrasing elements p.AllowElements("abbr", "acronym", "cite", "code", "dfn", "em", "figcaption", "mark", "s", "samp", "strong", "sub", "sup", "var") // "q" is permitted and "cite" is a URL and handled by URL policies p.AllowAttrs("cite").OnElements("q") // "time" is permitted p.AllowAttrs("datetime").Matching(ISO8601).OnElements("time") //////////////////// // Style elements // //////////////////// // block and inline elements that impart no semantic meaning but style the // document p.AllowElements("b", "i", "pre", "small", "strike", "tt", "u") // "style" is not permitted as we are not yet sanitising CSS and it is an // XSS attack vector ////////////////////// // HTML5 Formatting // ////////////////////// // "bdi" "bdo" are permitted p.AllowAttrs("dir").Matching(Direction).OnElements("bdi", "bdo") // "rp" "rt" "ruby" are permitted p.AllowElements("rp", "rt", "ruby") /////////////////////////// // HTML5 Change tracking // /////////////////////////// // "del" "ins" are permitted p.AllowAttrs("cite").Matching(Paragraph).OnElements("del", "ins") p.AllowAttrs("datetime").Matching(ISO8601).OnElements("del", "ins") /////////// // Lists // /////////// p.AllowLists() //////////// // Tables // //////////// p.AllowTables() /////////// // Forms // /////////// // By and large, forms are not permitted. However there are some form // elements that can be used to present data, and we do permit those // // "button" "fieldset" "input" "keygen" "label" "output" "select" "datalist" // "textarea" "optgroup" "option" are all not permitted // "meter" is permitted p.AllowAttrs( "value", "min", "max", "low", "high", "optimum", ).Matching(Number).OnElements("meter") // "progress" is permitted p.AllowAttrs("value", "max").Matching(Number).OnElements("progress") ////////////////////// // Embedded content // ////////////////////// // Vast majority not permitted // "audio" "canvas" "embed" "iframe" "object" "param" "source" "svg" "track" // "video" are all not permitted p.AllowImages() return p }
[ "func", "UGCPolicy", "(", ")", "*", "Policy", "{", "p", ":=", "NewPolicy", "(", ")", "\n\n", "///////////////////////", "// Global attributes //", "///////////////////////", "// \"class\" is not permitted as we are not allowing users to style their own", "// content", "p", ".", "AllowStandardAttributes", "(", ")", "\n\n", "//////////////////////////////", "// Global URL format policy //", "//////////////////////////////", "p", ".", "AllowStandardURLs", "(", ")", "\n\n", "////////////////////////////////", "// Declarations and structure //", "////////////////////////////////", "// \"xml\" \"xslt\" \"DOCTYPE\" \"html\" \"head\" are not permitted as we are", "// expecting user generated content to be a fragment of HTML and not a full", "// document.", "//////////////////////////", "// Sectioning root tags //", "//////////////////////////", "// \"article\" and \"aside\" are permitted and takes no attributes", "p", ".", "AllowElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// \"body\" is not permitted as we are expecting user generated content to be a fragment", "// of HTML and not a full document.", "// \"details\" is permitted, including the \"open\" attribute which can either", "// be blank or the value \"open\".", "p", ".", "AllowAttrs", "(", "\"", "\"", ",", ")", ".", "Matching", "(", "regexp", ".", "MustCompile", "(", "`(?i)^(|open)$`", ")", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n\n", "// \"fieldset\" is not permitted as we are not allowing forms to be created.", "// \"figure\" is permitted and takes no attributes", "p", ".", "AllowElements", "(", "\"", "\"", ")", "\n\n", "// \"nav\" is not permitted as it is assumed that the site (and not the user)", "// has defined navigation elements", "// \"section\" is permitted and takes no attributes", "p", ".", "AllowElements", "(", "\"", "\"", ")", "\n\n", "// \"summary\" is permitted and takes no attributes", "p", ".", "AllowElements", "(", "\"", "\"", ")", "\n\n", "//////////////////////////", "// Headings and footers //", "//////////////////////////", "// \"footer\" is not permitted as we expect user content to be a fragment and", "// not structural to this extent", "// \"h1\" through \"h6\" are permitted and take no attributes", "p", ".", "AllowElements", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// \"header\" is not permitted as we expect user content to be a fragment and", "// not structural to this extent", "// \"hgroup\" is permitted and takes no attributes", "p", ".", "AllowElements", "(", "\"", "\"", ")", "\n\n", "/////////////////////////////////////", "// Content grouping and separating //", "/////////////////////////////////////", "// \"blockquote\" is permitted, including the \"cite\" attribute which must be", "// a standard URL.", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n\n", "// \"br\" \"div\" \"hr\" \"p\" \"span\" \"wbr\" are permitted and take no attributes", "p", ".", "AllowElements", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "///////////", "// Links //", "///////////", "// \"a\" is permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n\n", "// \"area\" is permitted along with the attributes that map image maps work", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "regexp", ".", "MustCompile", "(", "`^([\\p{L}\\p{N}_-]+)$`", ")", ",", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "Paragraph", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "regexp", ".", "MustCompile", "(", "`^([0-9]+,)+[0-9]+$`", ")", ",", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "SpaceSeparatedTokens", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "regexp", ".", "MustCompile", "(", "`(?i)^(default|circle|rect|poly)$`", ")", ",", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "regexp", ".", "MustCompile", "(", "`(?i)^#[\\p{L}\\p{N}_-]+$`", ")", ",", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n\n", "// \"link\" is not permitted", "/////////////////////", "// Phrase elements //", "/////////////////////", "// The following are all inline phrasing elements", "p", ".", "AllowElements", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// \"q\" is permitted and \"cite\" is a URL and handled by URL policies", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n\n", "// \"time\" is permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "ISO8601", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n\n", "////////////////////", "// Style elements //", "////////////////////", "// block and inline elements that impart no semantic meaning but style the", "// document", "p", ".", "AllowElements", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// \"style\" is not permitted as we are not yet sanitising CSS and it is an", "// XSS attack vector", "//////////////////////", "// HTML5 Formatting //", "//////////////////////", "// \"bdi\" \"bdo\" are permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "Direction", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// \"rp\" \"rt\" \"ruby\" are permitted", "p", ".", "AllowElements", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "///////////////////////////", "// HTML5 Change tracking //", "///////////////////////////", "// \"del\" \"ins\" are permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "Paragraph", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "ISO8601", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "///////////", "// Lists //", "///////////", "p", ".", "AllowLists", "(", ")", "\n\n", "////////////", "// Tables //", "////////////", "p", ".", "AllowTables", "(", ")", "\n\n", "///////////", "// Forms //", "///////////", "// By and large, forms are not permitted. However there are some form", "// elements that can be used to present data, and we do permit those", "//", "// \"button\" \"fieldset\" \"input\" \"keygen\" \"label\" \"output\" \"select\" \"datalist\"", "// \"textarea\" \"optgroup\" \"option\" are all not permitted", "// \"meter\" is permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", ")", ".", "Matching", "(", "Number", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n\n", "// \"progress\" is permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Matching", "(", "Number", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n\n", "//////////////////////", "// Embedded content //", "//////////////////////", "// Vast majority not permitted", "// \"audio\" \"canvas\" \"embed\" \"iframe\" \"object\" \"param\" \"source\" \"svg\" \"track\"", "// \"video\" are all not permitted", "p", ".", "AllowImages", "(", ")", "\n\n", "return", "p", "\n", "}" ]
// UGCPolicy returns a policy aimed at user generated content that is a result // of HTML WYSIWYG tools and Markdown conversions. // // This is expected to be a fairly rich document where as much markup as // possible should be retained. Markdown permits raw HTML so we are basically // providing a policy to sanitise HTML5 documents safely but with the // least intrusion on the formatting expectations of the user.
[ "UGCPolicy", "returns", "a", "policy", "aimed", "at", "user", "generated", "content", "that", "is", "a", "result", "of", "HTML", "WYSIWYG", "tools", "and", "Markdown", "conversions", ".", "This", "is", "expected", "to", "be", "a", "fairly", "rich", "document", "where", "as", "much", "markup", "as", "possible", "should", "be", "retained", ".", "Markdown", "permits", "raw", "HTML", "so", "we", "are", "basically", "providing", "a", "policy", "to", "sanitise", "HTML5", "documents", "safely", "but", "with", "the", "least", "intrusion", "on", "the", "formatting", "expectations", "of", "the", "user", "." ]
89802068f71166e95c92040512bf2e11767721ed
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policies.go#L54-L253
train
microcosm-cc/bluemonday
helpers.go
AllowStandardAttributes
func (p *Policy) AllowStandardAttributes() { // "dir" "lang" are permitted as both language attributes affect charsets // and direction of text. p.AllowAttrs("dir").Matching(Direction).Globally() p.AllowAttrs( "lang", ).Matching(regexp.MustCompile(`[a-zA-Z]{2,20}`)).Globally() // "id" is permitted. This is pretty much as some HTML elements require this // to work well ("dfn" is an example of a "id" being value) // This does create a risk that JavaScript and CSS within your web page // might identify the wrong elements. Ensure that you select things // accurately p.AllowAttrs("id").Matching( regexp.MustCompile(`[a-zA-Z0-9\:\-_\.]+`), ).Globally() // "title" is permitted as it improves accessibility. p.AllowAttrs("title").Matching(Paragraph).Globally() }
go
func (p *Policy) AllowStandardAttributes() { // "dir" "lang" are permitted as both language attributes affect charsets // and direction of text. p.AllowAttrs("dir").Matching(Direction).Globally() p.AllowAttrs( "lang", ).Matching(regexp.MustCompile(`[a-zA-Z]{2,20}`)).Globally() // "id" is permitted. This is pretty much as some HTML elements require this // to work well ("dfn" is an example of a "id" being value) // This does create a risk that JavaScript and CSS within your web page // might identify the wrong elements. Ensure that you select things // accurately p.AllowAttrs("id").Matching( regexp.MustCompile(`[a-zA-Z0-9\:\-_\.]+`), ).Globally() // "title" is permitted as it improves accessibility. p.AllowAttrs("title").Matching(Paragraph).Globally() }
[ "func", "(", "p", "*", "Policy", ")", "AllowStandardAttributes", "(", ")", "{", "// \"dir\" \"lang\" are permitted as both language attributes affect charsets", "// and direction of text.", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "Direction", ")", ".", "Globally", "(", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ",", ")", ".", "Matching", "(", "regexp", ".", "MustCompile", "(", "`[a-zA-Z]{2,20}`", ")", ")", ".", "Globally", "(", ")", "\n\n", "// \"id\" is permitted. This is pretty much as some HTML elements require this", "// to work well (\"dfn\" is an example of a \"id\" being value)", "// This does create a risk that JavaScript and CSS within your web page", "// might identify the wrong elements. Ensure that you select things", "// accurately", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "regexp", ".", "MustCompile", "(", "`[a-zA-Z0-9\\:\\-_\\.]+`", ")", ",", ")", ".", "Globally", "(", ")", "\n\n", "// \"title\" is permitted as it improves accessibility.", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "Paragraph", ")", ".", "Globally", "(", ")", "\n", "}" ]
// AllowStandardAttributes will enable "id", "title" and the language specific // attributes "dir" and "lang" on all elements that are whitelisted
[ "AllowStandardAttributes", "will", "enable", "id", "title", "and", "the", "language", "specific", "attributes", "dir", "and", "lang", "on", "all", "elements", "that", "are", "whitelisted" ]
89802068f71166e95c92040512bf2e11767721ed
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/helpers.go#L145-L164
train
microcosm-cc/bluemonday
helpers.go
AllowLists
func (p *Policy) AllowLists() { // "ol" "ul" are permitted p.AllowAttrs("type").Matching(ListType).OnElements("ol", "ul") // "li" is permitted p.AllowAttrs("type").Matching(ListType).OnElements("li") p.AllowAttrs("value").Matching(Integer).OnElements("li") // "dl" "dt" "dd" are permitted p.AllowElements("dl", "dt", "dd") }
go
func (p *Policy) AllowLists() { // "ol" "ul" are permitted p.AllowAttrs("type").Matching(ListType).OnElements("ol", "ul") // "li" is permitted p.AllowAttrs("type").Matching(ListType).OnElements("li") p.AllowAttrs("value").Matching(Integer).OnElements("li") // "dl" "dt" "dd" are permitted p.AllowElements("dl", "dt", "dd") }
[ "func", "(", "p", "*", "Policy", ")", "AllowLists", "(", ")", "{", "// \"ol\" \"ul\" are permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "ListType", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// \"li\" is permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "ListType", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "Integer", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n\n", "// \"dl\" \"dt\" \"dd\" are permitted", "p", ".", "AllowElements", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// AllowLists will enabled ordered and unordered lists, as well as definition // lists
[ "AllowLists", "will", "enabled", "ordered", "and", "unordered", "lists", "as", "well", "as", "definition", "lists" ]
89802068f71166e95c92040512bf2e11767721ed
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/helpers.go#L235-L245
train
microcosm-cc/bluemonday
helpers.go
AllowTables
func (p *Policy) AllowTables() { // "table" is permitted p.AllowAttrs("height", "width").Matching(NumberOrPercent).OnElements("table") p.AllowAttrs("summary").Matching(Paragraph).OnElements("table") // "caption" is permitted p.AllowElements("caption") // "col" "colgroup" are permitted p.AllowAttrs("align").Matching(CellAlign).OnElements("col", "colgroup") p.AllowAttrs("height", "width").Matching( NumberOrPercent, ).OnElements("col", "colgroup") p.AllowAttrs("span").Matching(Integer).OnElements("colgroup", "col") p.AllowAttrs("valign").Matching( CellVerticalAlign, ).OnElements("col", "colgroup") // "thead" "tr" are permitted p.AllowAttrs("align").Matching(CellAlign).OnElements("thead", "tr") p.AllowAttrs("valign").Matching(CellVerticalAlign).OnElements("thead", "tr") // "td" "th" are permitted p.AllowAttrs("abbr").Matching(Paragraph).OnElements("td", "th") p.AllowAttrs("align").Matching(CellAlign).OnElements("td", "th") p.AllowAttrs("colspan", "rowspan").Matching(Integer).OnElements("td", "th") p.AllowAttrs("headers").Matching( SpaceSeparatedTokens, ).OnElements("td", "th") p.AllowAttrs("height", "width").Matching( NumberOrPercent, ).OnElements("td", "th") p.AllowAttrs( "scope", ).Matching( regexp.MustCompile(`(?i)(?:row|col)(?:group)?`), ).OnElements("td", "th") p.AllowAttrs("valign").Matching(CellVerticalAlign).OnElements("td", "th") p.AllowAttrs("nowrap").Matching( regexp.MustCompile(`(?i)|nowrap`), ).OnElements("td", "th") // "tbody" "tfoot" p.AllowAttrs("align").Matching(CellAlign).OnElements("tbody", "tfoot") p.AllowAttrs("valign").Matching( CellVerticalAlign, ).OnElements("tbody", "tfoot") }
go
func (p *Policy) AllowTables() { // "table" is permitted p.AllowAttrs("height", "width").Matching(NumberOrPercent).OnElements("table") p.AllowAttrs("summary").Matching(Paragraph).OnElements("table") // "caption" is permitted p.AllowElements("caption") // "col" "colgroup" are permitted p.AllowAttrs("align").Matching(CellAlign).OnElements("col", "colgroup") p.AllowAttrs("height", "width").Matching( NumberOrPercent, ).OnElements("col", "colgroup") p.AllowAttrs("span").Matching(Integer).OnElements("colgroup", "col") p.AllowAttrs("valign").Matching( CellVerticalAlign, ).OnElements("col", "colgroup") // "thead" "tr" are permitted p.AllowAttrs("align").Matching(CellAlign).OnElements("thead", "tr") p.AllowAttrs("valign").Matching(CellVerticalAlign).OnElements("thead", "tr") // "td" "th" are permitted p.AllowAttrs("abbr").Matching(Paragraph).OnElements("td", "th") p.AllowAttrs("align").Matching(CellAlign).OnElements("td", "th") p.AllowAttrs("colspan", "rowspan").Matching(Integer).OnElements("td", "th") p.AllowAttrs("headers").Matching( SpaceSeparatedTokens, ).OnElements("td", "th") p.AllowAttrs("height", "width").Matching( NumberOrPercent, ).OnElements("td", "th") p.AllowAttrs( "scope", ).Matching( regexp.MustCompile(`(?i)(?:row|col)(?:group)?`), ).OnElements("td", "th") p.AllowAttrs("valign").Matching(CellVerticalAlign).OnElements("td", "th") p.AllowAttrs("nowrap").Matching( regexp.MustCompile(`(?i)|nowrap`), ).OnElements("td", "th") // "tbody" "tfoot" p.AllowAttrs("align").Matching(CellAlign).OnElements("tbody", "tfoot") p.AllowAttrs("valign").Matching( CellVerticalAlign, ).OnElements("tbody", "tfoot") }
[ "func", "(", "p", "*", "Policy", ")", "AllowTables", "(", ")", "{", "// \"table\" is permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Matching", "(", "NumberOrPercent", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "Paragraph", ")", ".", "OnElements", "(", "\"", "\"", ")", "\n\n", "// \"caption\" is permitted", "p", ".", "AllowElements", "(", "\"", "\"", ")", "\n\n", "// \"col\" \"colgroup\" are permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "CellAlign", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Matching", "(", "NumberOrPercent", ",", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "Integer", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "CellVerticalAlign", ",", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// \"thead\" \"tr\" are permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "CellAlign", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "CellVerticalAlign", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// \"td\" \"th\" are permitted", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "Paragraph", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "CellAlign", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Matching", "(", "Integer", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "SpaceSeparatedTokens", ",", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Matching", "(", "NumberOrPercent", ",", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ",", ")", ".", "Matching", "(", "regexp", ".", "MustCompile", "(", "`(?i)(?:row|col)(?:group)?`", ")", ",", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "CellVerticalAlign", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "regexp", ".", "MustCompile", "(", "`(?i)|nowrap`", ")", ",", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// \"tbody\" \"tfoot\"", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "CellAlign", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "p", ".", "AllowAttrs", "(", "\"", "\"", ")", ".", "Matching", "(", "CellVerticalAlign", ",", ")", ".", "OnElements", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// AllowTables will enable a rich set of elements and attributes to describe // HTML tables
[ "AllowTables", "will", "enable", "a", "rich", "set", "of", "elements", "and", "attributes", "to", "describe", "HTML", "tables" ]
89802068f71166e95c92040512bf2e11767721ed
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/helpers.go#L249-L297
train
microcosm-cc/bluemonday
sanitize.go
SanitizeReader
func (p *Policy) SanitizeReader(r io.Reader) *bytes.Buffer { return p.sanitize(r) }
go
func (p *Policy) SanitizeReader(r io.Reader) *bytes.Buffer { return p.sanitize(r) }
[ "func", "(", "p", "*", "Policy", ")", "SanitizeReader", "(", "r", "io", ".", "Reader", ")", "*", "bytes", ".", "Buffer", "{", "return", "p", ".", "sanitize", "(", "r", ")", "\n", "}" ]
// SanitizeReader takes an io.Reader that contains a HTML fragment or document // and applies the given policy whitelist. // // It returns a bytes.Buffer containing the HTML that has been sanitized by the // policy. Errors during sanitization will merely return an empty result.
[ "SanitizeReader", "takes", "an", "io", ".", "Reader", "that", "contains", "a", "HTML", "fragment", "or", "document", "and", "applies", "the", "given", "policy", "whitelist", ".", "It", "returns", "a", "bytes", ".", "Buffer", "containing", "the", "HTML", "that", "has", "been", "sanitized", "by", "the", "policy", ".", "Errors", "during", "sanitization", "will", "merely", "return", "an", "empty", "result", "." ]
89802068f71166e95c92040512bf2e11767721ed
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/sanitize.go#L81-L83
train
microcosm-cc/bluemonday
policy.go
init
func (p *Policy) init() { if !p.initialized { p.elsAndAttrs = make(map[string]map[string]attrPolicy) p.globalAttrs = make(map[string]attrPolicy) p.allowURLSchemes = make(map[string]urlPolicy) p.setOfElementsAllowedWithoutAttrs = make(map[string]struct{}) p.setOfElementsToSkipContent = make(map[string]struct{}) p.initialized = true } }
go
func (p *Policy) init() { if !p.initialized { p.elsAndAttrs = make(map[string]map[string]attrPolicy) p.globalAttrs = make(map[string]attrPolicy) p.allowURLSchemes = make(map[string]urlPolicy) p.setOfElementsAllowedWithoutAttrs = make(map[string]struct{}) p.setOfElementsToSkipContent = make(map[string]struct{}) p.initialized = true } }
[ "func", "(", "p", "*", "Policy", ")", "init", "(", ")", "{", "if", "!", "p", ".", "initialized", "{", "p", ".", "elsAndAttrs", "=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "attrPolicy", ")", "\n", "p", ".", "globalAttrs", "=", "make", "(", "map", "[", "string", "]", "attrPolicy", ")", "\n", "p", ".", "allowURLSchemes", "=", "make", "(", "map", "[", "string", "]", "urlPolicy", ")", "\n", "p", ".", "setOfElementsAllowedWithoutAttrs", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "p", ".", "setOfElementsToSkipContent", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "p", ".", "initialized", "=", "true", "\n", "}", "\n", "}" ]
// init initializes the maps if this has not been done already
[ "init", "initializes", "the", "maps", "if", "this", "has", "not", "been", "done", "already" ]
89802068f71166e95c92040512bf2e11767721ed
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L117-L126
train
microcosm-cc/bluemonday
policy.go
Matching
func (abp *attrPolicyBuilder) Matching(regex *regexp.Regexp) *attrPolicyBuilder { abp.regexp = regex return abp }
go
func (abp *attrPolicyBuilder) Matching(regex *regexp.Regexp) *attrPolicyBuilder { abp.regexp = regex return abp }
[ "func", "(", "abp", "*", "attrPolicyBuilder", ")", "Matching", "(", "regex", "*", "regexp", ".", "Regexp", ")", "*", "attrPolicyBuilder", "{", "abp", ".", "regexp", "=", "regex", "\n\n", "return", "abp", "\n", "}" ]
// Matching allows a regular expression to be applied to a nascent attribute // policy, and returns the attribute policy. Calling this more than once will // replace the existing regexp.
[ "Matching", "allows", "a", "regular", "expression", "to", "be", "applied", "to", "a", "nascent", "attribute", "policy", "and", "returns", "the", "attribute", "policy", ".", "Calling", "this", "more", "than", "once", "will", "replace", "the", "existing", "regexp", "." ]
89802068f71166e95c92040512bf2e11767721ed
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L208-L213
train
microcosm-cc/bluemonday
policy.go
OnElements
func (abp *attrPolicyBuilder) OnElements(elements ...string) *Policy { for _, element := range elements { element = strings.ToLower(element) for _, attr := range abp.attrNames { if _, ok := abp.p.elsAndAttrs[element]; !ok { abp.p.elsAndAttrs[element] = make(map[string]attrPolicy) } ap := attrPolicy{} if abp.regexp != nil { ap.regexp = abp.regexp } abp.p.elsAndAttrs[element][attr] = ap } if abp.allowEmpty { abp.p.setOfElementsAllowedWithoutAttrs[element] = struct{}{} if _, ok := abp.p.elsAndAttrs[element]; !ok { abp.p.elsAndAttrs[element] = make(map[string]attrPolicy) } } } return abp.p }
go
func (abp *attrPolicyBuilder) OnElements(elements ...string) *Policy { for _, element := range elements { element = strings.ToLower(element) for _, attr := range abp.attrNames { if _, ok := abp.p.elsAndAttrs[element]; !ok { abp.p.elsAndAttrs[element] = make(map[string]attrPolicy) } ap := attrPolicy{} if abp.regexp != nil { ap.regexp = abp.regexp } abp.p.elsAndAttrs[element][attr] = ap } if abp.allowEmpty { abp.p.setOfElementsAllowedWithoutAttrs[element] = struct{}{} if _, ok := abp.p.elsAndAttrs[element]; !ok { abp.p.elsAndAttrs[element] = make(map[string]attrPolicy) } } } return abp.p }
[ "func", "(", "abp", "*", "attrPolicyBuilder", ")", "OnElements", "(", "elements", "...", "string", ")", "*", "Policy", "{", "for", "_", ",", "element", ":=", "range", "elements", "{", "element", "=", "strings", ".", "ToLower", "(", "element", ")", "\n\n", "for", "_", ",", "attr", ":=", "range", "abp", ".", "attrNames", "{", "if", "_", ",", "ok", ":=", "abp", ".", "p", ".", "elsAndAttrs", "[", "element", "]", ";", "!", "ok", "{", "abp", ".", "p", ".", "elsAndAttrs", "[", "element", "]", "=", "make", "(", "map", "[", "string", "]", "attrPolicy", ")", "\n", "}", "\n\n", "ap", ":=", "attrPolicy", "{", "}", "\n", "if", "abp", ".", "regexp", "!=", "nil", "{", "ap", ".", "regexp", "=", "abp", ".", "regexp", "\n", "}", "\n\n", "abp", ".", "p", ".", "elsAndAttrs", "[", "element", "]", "[", "attr", "]", "=", "ap", "\n", "}", "\n\n", "if", "abp", ".", "allowEmpty", "{", "abp", ".", "p", ".", "setOfElementsAllowedWithoutAttrs", "[", "element", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "if", "_", ",", "ok", ":=", "abp", ".", "p", ".", "elsAndAttrs", "[", "element", "]", ";", "!", "ok", "{", "abp", ".", "p", ".", "elsAndAttrs", "[", "element", "]", "=", "make", "(", "map", "[", "string", "]", "attrPolicy", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "abp", ".", "p", "\n", "}" ]
// OnElements will bind an attribute policy to a given range of HTML elements // and return the updated policy
[ "OnElements", "will", "bind", "an", "attribute", "policy", "to", "a", "given", "range", "of", "HTML", "elements", "and", "return", "the", "updated", "policy" ]
89802068f71166e95c92040512bf2e11767721ed
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L217-L246
train
microcosm-cc/bluemonday
policy.go
Globally
func (abp *attrPolicyBuilder) Globally() *Policy { for _, attr := range abp.attrNames { if _, ok := abp.p.globalAttrs[attr]; !ok { abp.p.globalAttrs[attr] = attrPolicy{} } ap := attrPolicy{} if abp.regexp != nil { ap.regexp = abp.regexp } abp.p.globalAttrs[attr] = ap } return abp.p }
go
func (abp *attrPolicyBuilder) Globally() *Policy { for _, attr := range abp.attrNames { if _, ok := abp.p.globalAttrs[attr]; !ok { abp.p.globalAttrs[attr] = attrPolicy{} } ap := attrPolicy{} if abp.regexp != nil { ap.regexp = abp.regexp } abp.p.globalAttrs[attr] = ap } return abp.p }
[ "func", "(", "abp", "*", "attrPolicyBuilder", ")", "Globally", "(", ")", "*", "Policy", "{", "for", "_", ",", "attr", ":=", "range", "abp", ".", "attrNames", "{", "if", "_", ",", "ok", ":=", "abp", ".", "p", ".", "globalAttrs", "[", "attr", "]", ";", "!", "ok", "{", "abp", ".", "p", ".", "globalAttrs", "[", "attr", "]", "=", "attrPolicy", "{", "}", "\n", "}", "\n\n", "ap", ":=", "attrPolicy", "{", "}", "\n", "if", "abp", ".", "regexp", "!=", "nil", "{", "ap", ".", "regexp", "=", "abp", ".", "regexp", "\n", "}", "\n\n", "abp", ".", "p", ".", "globalAttrs", "[", "attr", "]", "=", "ap", "\n", "}", "\n\n", "return", "abp", ".", "p", "\n", "}" ]
// Globally will bind an attribute policy to all HTML elements and return the // updated policy
[ "Globally", "will", "bind", "an", "attribute", "policy", "to", "all", "HTML", "elements", "and", "return", "the", "updated", "policy" ]
89802068f71166e95c92040512bf2e11767721ed
https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L250-L266
train