Skip to content

Instantly share code, notes, and snippets.

@f41gh7
Last active January 5, 2024 21:15
Show Gist options
  • Save f41gh7/a1ed97f330cda8c8b768fd2cbac16878 to your computer and use it in GitHub Desktop.
Save f41gh7/a1ed97f330cda8c8b768fd2cbac16878 to your computer and use it in GitHub Desktop.
metricsql.py

python wrapper for metricsql expr validation.

usage:

  1. build shared lib: go build -buildmode=c-shared -o library.so main.go
  2. use it
python3 metricsql.py 'not_exist(up)'`
failed to parse expr: not_exist(up), error: unsupported function "not_exist"

python3 metricsql.py 'rate(up) > 1'
expr: rate(up) > 1 is valid

NOTE result of parseExpr doesn't free memory, so it's recommened to use only for ad-hoc valition.

module example.com/metricsqlpy
go 1.21.0
require (
github.com/VictoriaMetrics/metrics v1.24.0 // indirect
github.com/VictoriaMetrics/metricsql v0.70.0 // indirect
github.com/valyala/fastrand v1.1.0 // indirect
github.com/valyala/histogram v1.2.0 // indirect
golang.org/x/sys v0.10.0 // indirect
)
package main
import (
"C"
"github.com/VictoriaMetrics/metricsql"
)
//export parseExpr
func parseExpr(expr *C.char) *C.char {
exprStr := C.GoString(expr)
_, err := metricsql.Parse(exprStr)
if err != nil {
return C.CString(err.Error())
}
return C.CString("")
}
func main(){}
import ctypes
import sys
metricsql = ctypes.cdll.LoadLibrary('./library.so')
validateExpr = sys.argv[1]
metricsql.parseExpr.restype = ctypes.c_char_p
metricsql.parseExpr.argtypes = [
ctypes.c_char_p
]
result = metricsql.parseExpr(validateExpr.encode())
if len(result) > 0:
print(f"failed to parse expr: {validateExpr}, error: {result.decode()}", )
exit(1)
print(f"expr: {validateExpr} is valid")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment