Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make format string thread safe #2086

Merged
merged 1 commit into from
Jul 26, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 61 additions & 25 deletions libbeat/common/fmtstr/formatevents.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"reflect"
"strconv"
"strings"
"sync"
"time"

"github.com/elastic/beats/libbeat/common"
Expand All @@ -25,29 +26,24 @@ import (
// `%{[field.name]:default value}`.
type EventFormatString struct {
formatter StringFormatter
ctx *eventEvalContext
fields []fieldInfo
timestamp bool
}

type eventFieldEvaler struct {
ctx *eventEvalContext
index int
}

type defaultEventFieldEvaler struct {
ctx *eventEvalContext
index int
defaultValue string
}

type eventTimestampEvaler struct {
ctx *eventEvalContext
formatter *dtfmt.Formatter
}

type eventFieldCompiler struct {
ctx *eventEvalContext
keys map[string]keyInfo
timestamp bool
index int
Expand All @@ -66,13 +62,33 @@ type keyInfo struct {
type eventEvalContext struct {
keys []string
ts time.Time
buf *bytes.Buffer
}

var (
errMissingKeys = errors.New("missing keys")
errConvertString = errors.New("can not convert to string")
)

var eventCtxPool = &sync.Pool{
New: func() interface{} { return &eventEvalContext{} },
}

func newEventCtx(sz int) *eventEvalContext {
ctx := eventCtxPool.Get().(*eventEvalContext)
if ctx.keys == nil || cap(ctx.keys) < sz {
ctx.keys = make([]string, 0, sz)
} else {
ctx.keys = ctx.keys[:0]
}

return ctx
}

func releaseCtx(c *eventEvalContext) {
eventCtxPool.Put(c)
}

// MustCompileEvent copmiles an event format string into an runnable
// EventFormatString. Generates a panic if compilation fails.
func MustCompileEvent(in string) *EventFormatString {
Expand All @@ -88,7 +104,6 @@ func MustCompileEvent(in string) *EventFormatString {
func CompileEvent(in string) (*EventFormatString, error) {
ctx := &eventEvalContext{}
efComp := &eventFieldCompiler{
ctx: ctx,
keys: map[string]keyInfo{},
index: 0,
timestamp: false,
Expand All @@ -110,7 +125,6 @@ func CompileEvent(in string) (*EventFormatString, error) {
ctx.keys = make([]string, len(keys))
efs := &EventFormatString{
formatter: sf,
ctx: ctx,
fields: keys,
timestamp: efComp.timestamp,
}
Expand Down Expand Up @@ -157,24 +171,43 @@ func (fs *EventFormatString) Fields() []string {
// Run executes the format string returning a new expanded string or an error
// if execution or event field expansion fails.
func (fs *EventFormatString) Run(event common.MapStr) (string, error) {
if err := fs.collectFields(event); err != nil {
ctx := newEventCtx(len(fs.fields))
defer releaseCtx(ctx)

if ctx.buf == nil {
ctx.buf = bytes.NewBuffer(nil)
} else {
ctx.buf.Reset()
}

if err := fs.collectFields(ctx, event); err != nil {
return "", err
}
err := fs.formatter.Eval(ctx, ctx.buf)
if err != nil {
return "", err
}
return fs.formatter.Run()
return ctx.buf.String(), nil
}

// Eval executes the format string, writing the resulting string into the provided output buffer. Returns error if execution or event field expansion fails.
func (fs *EventFormatString) Eval(out *bytes.Buffer, event common.MapStr) error {
if err := fs.collectFields(event); err != nil {
ctx := newEventCtx(len(fs.fields))
defer releaseCtx(ctx)

if err := fs.collectFields(ctx, event); err != nil {
return err
}
return fs.formatter.Eval(out)
return fs.formatter.Eval(ctx, out)
}

// collectFields tries to extract and convert all required fields into an array
// of strings.
func (fs *EventFormatString) collectFields(event common.MapStr) error {
for i, fi := range fs.fields {
func (fs *EventFormatString) collectFields(
ctx *eventEvalContext,
event common.MapStr,
) error {
for _, fi := range fs.fields {
s, err := fieldString(event, fi.path)
if err != nil {
if fi.required {
Expand All @@ -183,7 +216,7 @@ func (fs *EventFormatString) collectFields(event common.MapStr) error {

s = ""
}
fs.ctx.keys[i] = s
ctx.keys = append(ctx.keys, s)
}

if fs.timestamp {
Expand All @@ -194,9 +227,9 @@ func (fs *EventFormatString) collectFields(event common.MapStr) error {

switch t := timestamp.(type) {
case common.Time:
fs.ctx.ts = time.Time(t)
ctx.ts = time.Time(t)
case time.Time:
fs.ctx.ts = t
ctx.ts = t
default:
return errors.New("unknown timestamp type")
}
Expand Down Expand Up @@ -261,10 +294,10 @@ func (e *eventFieldCompiler) compileEventField(
idx := info.index

if len(ops) == 0 {
return &eventFieldEvaler{e.ctx, idx}, nil
return &eventFieldEvaler{idx}, nil
}

return &defaultEventFieldEvaler{e.ctx, idx, defaultValue}, nil
return &defaultEventFieldEvaler{idx, defaultValue}, nil
}

func (e *eventFieldCompiler) compileTimestamp(
Expand All @@ -281,34 +314,37 @@ func (e *eventFieldCompiler) compileTimestamp(
}

e.timestamp = true
return &eventTimestampEvaler{e.ctx, formatter}, nil
return &eventTimestampEvaler{formatter}, nil
}

func (e *eventFieldEvaler) Eval(out *bytes.Buffer) error {
func (e *eventFieldEvaler) Eval(c interface{}, out *bytes.Buffer) error {
type stringer interface {
String() string
}

s := e.ctx.keys[e.index]
ctx := c.(*eventEvalContext)
s := ctx.keys[e.index]
_, err := out.WriteString(s)
return err
}

func (e *defaultEventFieldEvaler) Eval(out *bytes.Buffer) error {
func (e *defaultEventFieldEvaler) Eval(c interface{}, out *bytes.Buffer) error {
type stringer interface {
String() string
}

s := e.ctx.keys[e.index]
ctx := c.(*eventEvalContext)
s := ctx.keys[e.index]
if s == "" {
s = e.defaultValue
}
_, err := out.WriteString(s)
return err
}

func (e *eventTimestampEvaler) Eval(out *bytes.Buffer) error {
_, err := e.formatter.Write(out, e.ctx.ts)
func (e *eventTimestampEvaler) Eval(c interface{}, out *bytes.Buffer) error {
ctx := c.(*eventEvalContext)
_, err := e.formatter.Write(out, ctx.ts)
return err
}

Expand Down
24 changes: 11 additions & 13 deletions libbeat/common/fmtstr/formatstring.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
type FormatEvaler interface {
// Eval will execute the format and writes the results into
// the provided output buffer. Returns error on failure.
Eval(out *bytes.Buffer) error
Eval(ctx interface{}, out *bytes.Buffer) error
}

// StringFormatter interface extends FormatEvaler adding support for querying
Expand All @@ -20,7 +20,7 @@ type StringFormatter interface {
FormatEvaler

// Run execute the formatter returning the generated string.
Run() (string, error)
Run(ctx interface{}) (string, error)

// IsConst returns true, if execution of formatter will always return the
// same constant string.
Expand All @@ -42,7 +42,6 @@ type constStringFormatter struct {
}

type execStringFormatter struct {
buf *bytes.Buffer
evalers []FormatEvaler
}

Expand Down Expand Up @@ -145,7 +144,6 @@ func compile(ctx *compileCtx, in string) (StringFormatter, error) {
// create executable string formatter
fmt := execStringFormatter{
evalers: evalers,
buf: bytes.NewBuffer(nil),
}
return fmt, nil
}
Expand Down Expand Up @@ -184,34 +182,34 @@ func optimize(in []FormatEvaler) []FormatEvaler {
return out
}

func (f constStringFormatter) Eval(out *bytes.Buffer) error {
func (f constStringFormatter) Eval(_ interface{}, out *bytes.Buffer) error {
_, err := out.WriteString(f.s)
return err
}

func (f constStringFormatter) Run() (string, error) {
func (f constStringFormatter) Run(_ interface{}) (string, error) {
return f.s, nil
}

func (f constStringFormatter) IsConst() bool {
return true
}

func (f execStringFormatter) Eval(out *bytes.Buffer) error {
func (f execStringFormatter) Eval(ctx interface{}, out *bytes.Buffer) error {
for _, evaler := range f.evalers {
if err := evaler.Eval(out); err != nil {
if err := evaler.Eval(ctx, out); err != nil {
return err
}
}
return nil
}

func (f execStringFormatter) Run() (string, error) {
f.buf.Reset()
if err := f.Eval(f.buf); err != nil {
func (f execStringFormatter) Run(ctx interface{}) (string, error) {
buf := bytes.NewBuffer(nil)
if err := f.Eval(ctx, buf); err != nil {
return "", err
}
return f.buf.String(), nil
return buf.String(), nil
}

func (f execStringFormatter) IsConst() bool {
Expand All @@ -224,7 +222,7 @@ func (e StringElement) compile(ctx *compileCtx) (FormatEvaler, error) {

// Eval write the string elements constant string value into
// output buffer.
func (e StringElement) Eval(out *bytes.Buffer) error {
func (e StringElement) Eval(_ interface{}, out *bytes.Buffer) error {
_, err := out.WriteString(e.s)
return err
}
Expand Down
2 changes: 1 addition & 1 deletion libbeat/common/fmtstr/formatstring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func TestFormatString(t *testing.T) {
}

// run string formatter
actual, err := sf.Run()
actual, err := sf.Run(nil)

// test validation
if test.dyn == nil {
Expand Down