github.com/DataDog/datadog-agent/pkg/security/secl@v0.55.0-devel.0.20240517055856-10c4965fea94/compiler/eval/context.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the Apache License Version 2.0.
     3  // This product includes software developed at Datadog (https://www.datadoghq.com/).
     4  // Copyright 2016-present Datadog, Inc.
     5  
     6  // Package eval holds eval related files
     7  package eval
     8  
     9  import (
    10  	"sync"
    11  	"time"
    12  )
    13  
    14  // Context describes the context used during a rule evaluation
    15  type Context struct {
    16  	Event Event
    17  
    18  	Registers Registers
    19  
    20  	// cache available across all the evaluations
    21  	StringCache map[string][]string
    22  	IntCache    map[string][]int
    23  	BoolCache   map[string][]bool
    24  
    25  	now time.Time
    26  }
    27  
    28  // Now return and cache the `now` timestamp
    29  func (c *Context) Now() time.Time {
    30  	if c.now.IsZero() {
    31  		c.now = time.Now()
    32  	}
    33  	return c.now
    34  }
    35  
    36  // SetEvent set the given event to the context
    37  func (c *Context) SetEvent(evt Event) {
    38  	c.Event = evt
    39  }
    40  
    41  // Reset the context
    42  func (c *Context) Reset() {
    43  	c.Event = nil
    44  	c.Registers = nil
    45  	c.now = time.Time{}
    46  
    47  	// as the cache should be low in entry, prefer to delete than re-alloc
    48  	for key := range c.StringCache {
    49  		delete(c.StringCache, key)
    50  	}
    51  	for key := range c.IntCache {
    52  		delete(c.IntCache, key)
    53  	}
    54  	for key := range c.BoolCache {
    55  		delete(c.BoolCache, key)
    56  	}
    57  }
    58  
    59  // NewContext return a new Context
    60  func NewContext(evt Event) *Context {
    61  	return &Context{
    62  		Event:       evt,
    63  		StringCache: make(map[string][]string),
    64  		IntCache:    make(map[string][]int),
    65  		BoolCache:   make(map[string][]bool),
    66  	}
    67  }
    68  
    69  // ContextPool defines a pool of context
    70  type ContextPool struct {
    71  	pool sync.Pool
    72  }
    73  
    74  // Get returns a context with the given event
    75  func (c *ContextPool) Get(evt Event) *Context {
    76  	ctx := c.pool.Get().(*Context)
    77  	ctx.SetEvent(evt)
    78  	return ctx
    79  }
    80  
    81  // Put returns the context to the pool
    82  func (c *ContextPool) Put(ctx *Context) {
    83  	ctx.Reset()
    84  	c.pool.Put(ctx)
    85  }
    86  
    87  // NewContextPool returns a new context pool
    88  func NewContextPool() *ContextPool {
    89  	return &ContextPool{
    90  		pool: sync.Pool{
    91  			New: func() interface{} { return NewContext(nil) },
    92  		},
    93  	}
    94  }