Skip to content
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
69 changes: 33 additions & 36 deletions libbeat/processors/script/javascript/beatevent_v0.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
package javascript

import (
"errors"
"fmt"
"slices"

"github.com/dop251/goja"

Expand All @@ -28,8 +28,8 @@ import (
)

// IMPORTANT:
// This is the user facing API within Javascript processors. Do not make
// breaking changes to the JS methods. If you must make breaking changes then
// This is the user-facing API within JavaScript processors. Do not make
// breaking changes to the JS methods. If you must make breaking changes, then
// create a new version and require the user to specify an API version in their
// configuration (e.g. api_version: 2).

Expand All @@ -52,48 +52,47 @@ func newBeatEventV0(s Session) (Event, error) {
func newBeatEventV0Constructor(s Session) func(call goja.ConstructorCall) *goja.Object {
return func(call goja.ConstructorCall) *goja.Object {
if len(call.Arguments) != 1 {
panic(errors.New("Event constructor requires one argument"))
panic("Event constructor requires one argument")
}

a0 := call.Argument(0).Export()

var fields mapstr.M
switch v := a0.(type) {
case map[string]interface{}:
case map[string]any:
fields = v
case mapstr.M:
fields = v
default:
panic(fmt.Errorf("Event constructor requires a "+
"map[string]interface{} argument but got %T", a0))
panic(fmt.Sprintf("Event constructor requires map[string]interface{} argument but got %T", a0))
}

evt := &beatEventV0{
vm: s.Runtime(),
obj: call.This,
}
evt.init()
evt.reset(&beat.Event{Fields: fields})
_ = evt.reset(&beat.Event{Fields: fields})
return nil
}
}

func (e *beatEventV0) init() {
e.obj.Set("Get", e.get)
e.obj.Set("Put", e.put)
e.obj.Set("Rename", e.rename)
e.obj.Set("Delete", e.delete)
e.obj.Set("Cancel", e.cancel)
e.obj.Set("Tag", e.tag)
e.obj.Set("AppendTo", e.appendTo)
_ = e.obj.Set("Get", e.get)
_ = e.obj.Set("Put", e.put)
_ = e.obj.Set("Rename", e.rename)
_ = e.obj.Set("Delete", e.delete)
_ = e.obj.Set("Cancel", e.cancel)
_ = e.obj.Set("Tag", e.tag)
_ = e.obj.Set("AppendTo", e.appendTo)
}

// reset the event so that it can be reused to wrap another event.
func (e *beatEventV0) reset(b *beat.Event) error {
e.inner = b
e.cancelled = false
e.obj.Set("_private", e)
e.obj.Set("fields", e.vm.ToValue(e.inner.Fields))
_ = e.obj.Set("_private", e)
_ = e.obj.Set("fields", e.vm.ToValue(e.inner.Fields))
return nil
}

Expand All @@ -103,13 +102,13 @@ func (e *beatEventV0) Wrapped() *beat.Event {
}

// JSObject returns the goja.Value that represents the event within the
// Javascript runtime.
// JavaScript runtime.
func (e *beatEventV0) JSObject() goja.Value {
return e.obj
}

// get returns the specified field. If the field does not exist then null is
// returned. If no field is specified then it returns entire object.
// get returns the specified field. If the field does not exist, then null is
// returned. If no field is specified, then it returns an entire object.
//
// // javascript
// var dataset = evt.Get("event.dataset");
Expand All @@ -129,7 +128,7 @@ func (e *beatEventV0) get(call goja.FunctionCall) goja.Value {
}

// put writes a value to the event. If there was a previous value assigned to
// the given field then the old object is returned. It throws an exception if
// the given field, then the old object is returned. It throws an exception if
// you try to write a to a field where one of the intermediate values is not
// an object.
//
Expand All @@ -138,7 +137,7 @@ func (e *beatEventV0) get(call goja.FunctionCall) goja.Value {
// evt.Put("geo.location", {"lon": -73.614830, "lat": 45.505918});
func (e *beatEventV0) put(call goja.FunctionCall) goja.Value {
if len(call.Arguments) != 2 {
panic(errors.New("Put requires two arguments (key and value)"))
panic("Put requires two arguments (key and value)")
}

key := call.Argument(0).String()
Expand All @@ -157,7 +156,7 @@ func (e *beatEventV0) put(call goja.FunctionCall) goja.Value {
// evt.Rename("src_ip", "source.ip");
func (e *beatEventV0) rename(call goja.FunctionCall) goja.Value {
if len(call.Arguments) != 2 {
panic(errors.New("Rename requires two arguments (from and to)"))
panic("Rename requires two arguments (from and to)")
}

from := call.Argument(0).String()
Expand All @@ -181,7 +180,7 @@ func (e *beatEventV0) rename(call goja.FunctionCall) goja.Value {

if _, err = e.inner.PutValue(to, fromValue); err != nil {
// Undo
e.inner.PutValue(from, fromValue)
_, _ = e.inner.PutValue(from, fromValue)
return e.vm.ToValue(false)
}

Expand All @@ -194,7 +193,7 @@ func (e *beatEventV0) rename(call goja.FunctionCall) goja.Value {
// evt.Delete("http.request.headers.authorization");
func (e *beatEventV0) delete(call goja.FunctionCall) goja.Value {
if len(call.Arguments) != 1 {
panic(errors.New("Delete requires one argument"))
panic("Delete requires one argument")
}

key := call.Argument(0).String()
Expand All @@ -210,14 +209,14 @@ func (e *beatEventV0) IsCancelled() bool {
return e.cancelled
}

// Cancel marks the event as cancelled. When the processor returns the event
// Cancel marks the event as cancelled. When the processor returns, the event
// will be dropped.
func (e *beatEventV0) Cancel() {
e.cancelled = true
}

// cancel marks the event as cancelled.
func (e *beatEventV0) cancel(call goja.FunctionCall) goja.Value {
func (e *beatEventV0) cancel(goja.FunctionCall) goja.Value {
e.cancelled = true
return goja.Undefined()
}
Expand All @@ -229,7 +228,7 @@ func (e *beatEventV0) cancel(call goja.FunctionCall) goja.Value {
// evt.Tag("_parse_failure");
func (e *beatEventV0) tag(call goja.FunctionCall) goja.Value {
if len(call.Arguments) != 1 {
panic(errors.New("Tag requires one argument"))
panic("Tag requires one argument")
}

tag := call.Argument(0).String()
Expand All @@ -242,14 +241,14 @@ func (e *beatEventV0) tag(call goja.FunctionCall) goja.Value {

// appendTo is a specialized Put method that converts any existing value to
// an array and appends the value if it does not already exist. If there is an
// existing value that's not a string or array of strings then an exception is
// existing value that's not a string or array of strings, then an exception is
// thrown.
//
// // javascript
// evt.AppendTo("error.message", "invalid file hash");
func (e *beatEventV0) appendTo(call goja.FunctionCall) goja.Value {
if len(call.Arguments) != 2 {
panic(errors.New("AppendTo requires two arguments (field and value)"))
panic("AppendTo requires two arguments (field and value)")
}

field := call.Argument(0).String()
Expand All @@ -275,14 +274,12 @@ func appendString(m mapstr.M, field, value string, alwaysArray bool) error {
m.Put(field, []string{v, value})
}
case []string:
for _, existingTag := range v {
if value == existingTag {
// Duplicate
return nil
}
if slices.Contains(v, value) {
// Duplicate
return nil
}
m.Put(field, append(v, value))
case []interface{}:
case []any:
for _, existingTag := range v {
if value == existingTag {
// Duplicate
Expand Down
4 changes: 2 additions & 2 deletions libbeat/processors/script/javascript/beatevent_v0_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ func TestBeatEventV0(t *testing.T) {
// Validate that the processor's metrics exist.
var found bool
prefix := fmt.Sprintf("processor.javascript.%s.histogram.process_time", tc.name)
reg.Do(monitoring.Full, func(name string, v interface{}) {
reg.Do(monitoring.Full, func(name string, v any) {
if !found && strings.HasPrefix(name, prefix) {
found = true
}
Expand All @@ -221,7 +221,7 @@ func BenchmarkBeatEventV0(b *testing.B) {

event := testEvent()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, err := p.Run(event)
if err != nil {
b.Fatal(err)
Expand Down
20 changes: 10 additions & 10 deletions libbeat/processors/script/javascript/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,17 @@ import (
"time"
)

// Config defines the Javascript source files to use for the processor.
// Config defines the JavaScript source files to use for the processor.
type Config struct {
Tag string `config:"tag"` // Processor ID for debug and metrics.
Source string `config:"source"` // Inline script to execute.
File string `config:"file"` // Source file.
Files []string `config:"files"` // Multiple source files.
Params map[string]interface{} `config:"params"` // Parameters to pass to script.
Timeout time.Duration `config:"timeout" validate:"min=0"` // Execution timeout.
TagOnException string `config:"tag_on_exception"` // Tag to add to events when an exception happens.
MaxCachedSessions int `config:"max_cached_sessions" validate:"min=0"` // Max. number of cached VM sessions.
OnlyCachedSessions bool `config:"only_cached_sessions"` // Only use cached VM sessions.
Tag string `config:"tag"` // Processor ID for debug and metrics.
Source string `config:"source"` // Inline script to execute.
File string `config:"file"` // Source file.
Files []string `config:"files"` // Multiple source files.
Params map[string]any `config:"params"` // Parameters to pass to script.
Timeout time.Duration `config:"timeout" validate:"min=0"` // Execution timeout.
TagOnException string `config:"tag_on_exception"` // Tag to add to events when an exception happens.
MaxCachedSessions int `config:"max_cached_sessions" validate:"min=0"` // Max. number of cached VM sessions.
OnlyCachedSessions bool `config:"only_cached_sessions"` // Only use cached VM sessions.
}

// Validate returns an error if one (and only one) option is not set.
Expand Down
23 changes: 11 additions & 12 deletions libbeat/processors/script/javascript/javascript.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ type jsProcessor struct {
stats *processorStats
}

// New constructs a new Javascript processor.
// New constructs a new JavaScript processor.
func New(c *config.C, log *logp.Logger) (beat.Processor, error) {
conf := defaultConfig()
if err := c.Unpack(&conf); err != nil {
Expand All @@ -57,7 +57,7 @@ func New(c *config.C, log *logp.Logger) (beat.Processor, error) {
return NewFromConfig(conf, monitoring.Default, log)
}

// NewFromConfig constructs a new Javascript processor from the given config
// NewFromConfig constructs a new JavaScript processor from the given config
// object. It loads the sources, compiles them, and validates the entry point.
func NewFromConfig(c Config, reg *monitoring.Registry, logger *logp.Logger) (beat.Processor, error) {
err := c.Validate()
Expand All @@ -66,12 +66,11 @@ func NewFromConfig(c Config, reg *monitoring.Registry, logger *logp.Logger) (bea
}

var sourceFile string
var sourceCode []byte

var sourceCode string
switch {
case c.Source != "":
sourceFile = "inline.js"
sourceCode = []byte(c.Source)
sourceCode = c.Source
case c.File != "":
sourceFile, sourceCode, err = loadSources(c.File)
case len(c.Files) > 0:
Expand All @@ -82,7 +81,7 @@ func NewFromConfig(c Config, reg *monitoring.Registry, logger *logp.Logger) (bea
}

// Validate processor source code.
prog, err := goja.Compile(sourceFile, string(sourceCode), true)
prog, err := goja.Compile(sourceFile, sourceCode, true)
if err != nil {
return nil, err
}
Expand All @@ -102,7 +101,7 @@ func NewFromConfig(c Config, reg *monitoring.Registry, logger *logp.Logger) (bea
}

// loadSources loads javascript source from files.
func loadSources(files ...string) (string, []byte, error) {
func loadSources(files ...string) (string, string, error) {
var sources []string
buf := new(bytes.Buffer)

Expand Down Expand Up @@ -131,7 +130,7 @@ func loadSources(files ...string) (string, []byte, error) {
if hasMeta(filePath) {
matches, err := filepath.Glob(filePath)
if err != nil {
return "", nil, err
return "", "", err
}
sources = append(sources, matches...)
} else {
Expand All @@ -140,17 +139,17 @@ func loadSources(files ...string) (string, []byte, error) {
}

if len(sources) == 0 {
return "", nil, fmt.Errorf("no sources were found in %v",
return "", "", fmt.Errorf("no sources were found in %v",
strings.Join(files, ", "))
}

for _, name := range sources {
if err := readFile(name); err != nil {
return "", nil, err
return "", "", err
}
}

return strings.Join(sources, ";"), buf.Bytes(), nil
return strings.Join(sources, ";"), buf.String(), nil
}

func annotateError(id string, err error) error {
Expand All @@ -164,7 +163,7 @@ func annotateError(id string, err error) error {
}

// Run executes the processor on the given it event. It invokes the
// process function defined in the Javascript source.
// process function defined in the JavaScript source.
func (p *jsProcessor) Run(event *beat.Event) (*beat.Event, error) {
s := p.sessionPool.Get()
defer p.sessionPool.Put(s)
Expand Down
Loading