Skip to content
Draft
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
2 changes: 2 additions & 0 deletions CEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,8 @@ jq(".[] | select(.age > 25)", [{ name: "John", age: 30 }, { name: "Jane", age: 2

## kubernetes

`k8s.cpuAsMillicores` and `k8s.memoryAsBytes` are always available. The other `k8s.*` functions need `gomplate.Register(kubernetes.Extension())`; see [Optional function groups](README.md#optional-function-groups).

### k8s.cpuAsMillicores

Returns the millicores of a Kubernetes CPU resource string.
Expand Down
19 changes: 16 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,26 @@ Flanksource Gomplate is a fork of [hairyhenderson/gomplate](https://github.com/h
- **CEL (Common Expression Language)** – [CEL](https://cel.dev/) support with:
- Standard CEL operators and built-ins
- [cel-go extensions](https://github.com/cel-expr/cel-go/tree/v0.31.0/ext) (strings, encoders, lists, math, sets)
- Kubernetes-specific helpers (`k8s.*`)
- Kubernetes-specific helpers (`k8s.*`); health, status, neat and topology are [opt-in](#optional-function-groups)
- AWS helpers (`aws.*`)
- Many gomplate functions remapped into CEL (`base64`, `math`, `random`, `regexp`, `filepath`, `crypto`, `sets`, etc.)
- Optional-type support (`obj.?field.orValue("default")`)
- **JavaScript (otto)** – Lightweight JS evaluation via [otto](https://github.com/robertkrimen/otto)
- **JavaScript (otto)** – Lightweight JS evaluation via [otto](https://github.com/robertkrimen/otto), [opt-in](#optional-function-groups)
- **Struct templating** – Walk Go structs/maps and apply templates to string fields in-place

## Optional function groups

The Kubernetes health, status, neat and topology functions and JavaScript templates pull in
Kubernetes, Lua and otto dependencies, so the core package does not import them. A program
that needs them imports `github.com/flanksource/gomplate/v4/kubernetes` and
`github.com/flanksource/gomplate/v4/js` and registers them once at startup with
`gomplate.Register(kubernetes.Extension(), js.Extension())`.

Without `kubernetes.Extension()`, CEL expressions such as `k8s.isHealthy(pod)` fail with an
undeclared reference and Go templates fail to parse `isHealthy`. Without `js.Extension()`,
`Template.Javascript` returns an error. `k8s.cpuAsMillicores`, `k8s.memoryAsBytes` and the
list, URL and regex functions stay in the core.

## Quick Reference

| Language | Example | Documentation |
Expand Down Expand Up @@ -51,7 +64,7 @@ true ? "yes" : "no"
obj.?field.orValue("default")
obj.?a.?b.orValue("fallback")

# Kubernetes
# Kubernetes (k8s.isHealthy needs kubernetes.Extension())
k8s.isHealthy(pod)
k8s.cpuAsMillicores("500m") // 500
k8s.memoryAsBytes("1Gi")
Expand Down
75 changes: 47 additions & 28 deletions cel.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"regexp"
"sort"
"sync"
"sync/atomic"

"cel.dev/cel-go/cel"
"cel.dev/cel-go/common/types"
Expand All @@ -17,26 +18,27 @@ import (
"github.com/flanksource/gomplate/v4/celvalues"
"github.com/flanksource/gomplate/v4/conv"
"github.com/flanksource/gomplate/v4/funcs"
"github.com/flanksource/gomplate/v4/kubernetes"
"github.com/flanksource/gomplate/v4/nilsafe"
"github.com/flanksource/gomplate/v4/strings"
)

const celRegexProgramSizeLimit = 10_000

// staticCelEnvOptions returns the environment-independent CEL options: the
// generated functions, the kubernetes library, the cel-go extensions, the
// standard library and gomplate's own custom functions. They are identical on
// every call, so they are built once into the cached base environment (see
// baseCelEnv) instead of being reconstructed for every expression compile.
// generated functions, the list, URL, regex and quantity functions, the
// cel-go extensions, the standard library, gomplate's own custom functions and
// those of the registered extensions. They change only when Register is called,
// so they are built once into the cached base environment (see baseCelEnv)
// instead of being reconstructed for every expression compile.
//
// Built once into the cached base env (see baseCelEnv), so this is not sized for
// speed. Starting from a nil slice also guarantees the first append copies
// funcs.CelEnvOption rather than aliasing its backing array.
func staticCelEnvOptions() []cel.EnvOption {
var opts []cel.EnvOption //nolint:prealloc
opts = append(opts, funcs.CelEnvOption...)
opts = append(opts, kubernetes.Library()...)
opts = append(opts, Lists(), URLs(), Regex())
opts = append(opts, cpuAsMillicoresFunction(), memoryAsBytesFunction())
// gomplate never estimates cost, and cel-go recompiles every registered cost model on each
// Env.Extend, so the extensions come from celext with their cost models left out.
opts = append(opts,
Expand All @@ -57,35 +59,52 @@ func staticCelEnvOptions() []cel.EnvOption {
opts = append(opts, statisticsCelOptions()...)
opts = append(opts, celvalues.Library())
opts = append(opts, cel.RegexProgramSizeLimit(celRegexProgramSizeLimit))
opts = append(opts, extensionCelOptions()...)
return opts
}

// baseCelEnv builds, exactly once, a CEL environment that holds only the static,
// environment-independent options. RunExpressionContext layers the per-call
// variables, registered native types and caller-provided functions on top with
// Env.Extend.
// baseCelEnv builds, once per set of registered extensions, a CEL environment that
// holds only the static, environment-independent options. RunExpressionContext layers
// the per-call variables, registered native types and caller-provided functions on top
// with Env.Extend.
//
// This is the dominant CEL allocation/CPU saving: kubernetes.Library() and the
// validation of its declarations are paid once for the lifetime of the process
// instead of on every compile. EagerlyValidateDeclarations forces the base env
// to validate its declarations up front so Extend reuses them and only validates
// the small per-call delta.
// This is the dominant CEL allocation/CPU saving: the function libraries and the
// validation of their declarations are paid once instead of on every compile.
// EagerlyValidateDeclarations forces the base env to validate its declarations up
// front so Extend reuses them and only validates the small per-call delta.
//
// Env.Extend uses copy-on-write and never mutates the receiver, so the cached
// base env is safe to share across goroutines.
var strictBaseCelEnv = sync.OnceValues(func() (*cel.Env, error) {
opts := staticCelEnvOptions()
opts = append(opts, cel.EagerlyValidateDeclarations(true))
return cel.NewEnv(opts...)
})

var baseCelEnv = sync.OnceValues(func() (*cel.Env, error) {
base, err := strictBaseCelEnv()
if err != nil {
return nil, err
}
return base.Extend(nilsafe.Library(nilsafe.WithZeroValues()))
})
func baseCelEnv() (*cel.Env, error) { return celBaseEnvs.Load().nilSafe() }

func strictBaseCelEnv() (*cel.Env, error) { return celBaseEnvs.Load().strict() }

type celBaseEnvSet struct {
strict, nilSafe func() (*cel.Env, error)
}

var celBaseEnvs atomic.Pointer[celBaseEnvSet]

func init() { resetCelBaseEnvs() }

// resetCelBaseEnvs drops the built base environments, so the next expression builds
// them again from the currently registered extensions.
func resetCelBaseEnvs() {
set := &celBaseEnvSet{}
set.strict = sync.OnceValues(func() (*cel.Env, error) {
opts := staticCelEnvOptions()
opts = append(opts, cel.EagerlyValidateDeclarations(true))
return cel.NewEnv(opts...)
})
set.nilSafe = sync.OnceValues(func() (*cel.Env, error) {
base, err := set.strict()
if err != nil {
return nil, err
}
return base.Extend(nilsafe.Library(nilsafe.WithZeroValues()))
})
celBaseEnvs.Store(set)
}

// GetCelEnv returns the full set of CEL env options: the static options, any
// types registered via RegisterType, and one variable per environment key.
Expand Down
10 changes: 5 additions & 5 deletions kubernetes/lists.go → cel_lists.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package kubernetes
package gomplate

import (
"fmt"
Expand Down Expand Up @@ -151,11 +151,11 @@ var listsLibraryDecls = map[string][]cel.FunctionOpt{
}),
"max": templatedOverloads(comparableTypes, func(name string, paramType *cel.Type) cel.FunctionOpt {
return cel.MemberOverload(fmt.Sprintf("list_%s_max_%s", name, name),
[]*cel.Type{cel.ListType(paramType)}, paramType, cel.UnaryBinding(max()))
[]*cel.Type{cel.ListType(paramType)}, paramType, cel.UnaryBinding(listMax()))
}),
"min": templatedOverloads(comparableTypes, func(name string, paramType *cel.Type) cel.FunctionOpt {
return cel.MemberOverload(fmt.Sprintf("list_%s_min_%s", name, name),
[]*cel.Type{cel.ListType(paramType)}, paramType, cel.UnaryBinding(min()))
[]*cel.Type{cel.ListType(paramType)}, paramType, cel.UnaryBinding(listMin()))
}),
"indexOf": {
cel.MemberOverload("list_a_index_of_int", []*cel.Type{cel.ListType(paramA), paramA}, cel.IntType,
Expand Down Expand Up @@ -242,11 +242,11 @@ func sum(init func() ref.Val) functions.UnaryOp {
}
}

func min() functions.UnaryOp {
func listMin() functions.UnaryOp {
return cmp("min", types.IntOne)
}

func max() functions.UnaryOp {
func listMax() functions.UnaryOp {
return cmp("max", types.IntNegOne)
}

Expand Down
34 changes: 34 additions & 0 deletions cel_quantity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package gomplate

import (
"cel.dev/cel-go/cel"
"cel.dev/cel-go/common/types"
"cel.dev/cel-go/common/types/ref"
"github.com/flanksource/gomplate/v4/conv"
)

func cpuAsMillicoresFunction() cel.EnvOption {
return cel.Function("k8s.cpuAsMillicores",
cel.Overload("k8s.cpuAsMillicores_string",
[]*cel.Type{cel.StringType},
cel.IntType,
cel.UnaryBinding(func(obj ref.Val) ref.Val {
objVal := conv.ToString(obj.Value())
return types.Int(conv.CPUAsMillicores(objVal))
}),
),
)
}

func memoryAsBytesFunction() cel.EnvOption {
return cel.Function("k8s.memoryAsBytes",
cel.Overload("k8s.memoryAsBytes_string",
[]*cel.Type{cel.StringType},
cel.IntType,
cel.UnaryBinding(func(obj ref.Val) ref.Val {
objVal := conv.ToString(obj.Value())
return types.Int(conv.MemoryAsBytes(objVal))
}),
),
)
}
2 changes: 1 addition & 1 deletion kubernetes/regex.go → cel_regex.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package kubernetes
package gomplate

import (
"regexp"
Expand Down
2 changes: 1 addition & 1 deletion kubernetes/url.go → cel_url.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package kubernetes
package gomplate

import (
"fmt"
Expand Down
3 changes: 3 additions & 0 deletions cmd/ceval/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"os"

"github.com/flanksource/gomplate/v4"
"github.com/flanksource/gomplate/v4/js"
"github.com/flanksource/gomplate/v4/kubernetes"
"github.com/flanksource/gomplate/v4/version"
"gopkg.in/yaml.v3"
)
Expand Down Expand Up @@ -105,5 +107,6 @@ func run(args []string, stdout, stderr io.Writer) int {
}

func main() {
gomplate.Register(kubernetes.Extension(), js.Extension())
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
}
4 changes: 4 additions & 0 deletions cmd/ceval/serve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@ import (
"net/http/httptest"
"testing"

gomplate "github.com/flanksource/gomplate/v4"
"github.com/flanksource/gomplate/v4/js"
"github.com/flanksource/gomplate/v4/kubernetes"
"github.com/flanksource/gomplate/v4/playground"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

func TestServe(t *testing.T) {
RegisterFailHandler(Fail)
gomplate.Register(kubernetes.Extension(), js.Extension())
RunSpecs(t, "ceval serve")
}

Expand Down
4 changes: 4 additions & 0 deletions cmd/genmonarch/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@ import (
"path/filepath"
"sort"

gomplate "github.com/flanksource/gomplate/v4"
"github.com/flanksource/gomplate/v4/genmonarch"
"github.com/flanksource/gomplate/v4/js"
"github.com/flanksource/gomplate/v4/kubernetes"
)

func main() {
gomplate.Register(kubernetes.Extension(), js.Extension())
out := flag.String("out", "web/packages/lang/src/generated", "directory to write the generated definitions into")
check := flag.Bool("check", false, "verify the checked-in files are up to date instead of writing them; exits non-zero on drift")
flag.Parse()
Expand Down
4 changes: 4 additions & 0 deletions cmd/playground/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,15 @@ import (
"os"
"time"

gomplate "github.com/flanksource/gomplate/v4"
"github.com/flanksource/gomplate/v4/js"
"github.com/flanksource/gomplate/v4/kubernetes"
"github.com/flanksource/gomplate/v4/playground"
"github.com/flanksource/gomplate/v4/web/packages/lang"
)

func main() {
gomplate.Register(kubernetes.Extension(), js.Extension())
addr := flag.String("addr", ":8321", "address to listen on")
timeout := flag.Duration("timeout", 5*time.Second, "ceiling on one evaluation")
flag.Parse()
Expand Down
4 changes: 4 additions & 0 deletions cmd/wasm/eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@ import (
"encoding/json"
"testing"

gomplate "github.com/flanksource/gomplate/v4"
"github.com/flanksource/gomplate/v4/js"
"github.com/flanksource/gomplate/v4/kubernetes"
"github.com/flanksource/gomplate/v4/playground"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

func TestWASM(t *testing.T) {
RegisterFailHandler(Fail)
gomplate.Register(kubernetes.Extension(), js.Extension())
RunSpecs(t, "WASM bridge")
}

Expand Down
9 changes: 8 additions & 1 deletion cmd/wasm/main_js.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@

package main

import "syscall/js"
import (
"syscall/js"

gomplate "github.com/flanksource/gomplate/v4"
gomplatejs "github.com/flanksource/gomplate/v4/js"
"github.com/flanksource/gomplate/v4/kubernetes"
)

func main() {
gomplate.Register(kubernetes.Extension(), gomplatejs.Extension())
evaluate := js.FuncOf(func(_ js.Value, args []js.Value) any {
if len(args) != 1 || args[0].Type() != js.TypeString {
return `{"result":"","durationMs":0,"error":{"message":"expected one JSON request string"}}`
Expand Down
36 changes: 36 additions & 0 deletions conv/quantity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package conv

import "strings"

// CPUAsMillicores converts a Kubernetes CPU quantity such as "500m", "250000000n" or "0.5"
// to millicores.
func CPUAsMillicores(objVal string) int64 {
if strings.HasSuffix(objVal, "m") {
return ToInt64(strings.ReplaceAll(objVal, "m", ""))
}

if strings.HasSuffix(objVal, "n") {
return ToInt64(strings.ReplaceAll(objVal, "n", "")) / (1000 * 1000)
}

return int64(ToFloat64(objVal) * 1000)
}

// MemoryAsBytes converts a Kubernetes memory quantity such as "1Gi", "512Mi" or "64Ki" to
// bytes.
func MemoryAsBytes(objVal string) int64 {
objVal = strings.ToLower(objVal)

var memory int64
switch {
case strings.HasSuffix(objVal, "gi"):
memory = int64(ToFloat64(strings.ReplaceAll(objVal, "gi", "")) * 1024 * 1024 * 1024)
case strings.HasSuffix(objVal, "mi"):
memory = int64(ToFloat64(strings.ReplaceAll(objVal, "mi", "")) * 1024 * 1024)
case strings.HasSuffix(objVal, "ki"):
memory = int64(ToFloat64(strings.ReplaceAll(objVal, "ki", "")) * 1024)
default:
memory = ToInt64(objVal)
}
return memory
}
Loading
Loading