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

Crashd API should support ability to inject external built-in Starlark functions #231

Open
vladimirvivien opened this issue Dec 2, 2021 · 0 comments

Comments

@vladimirvivien
Copy link
Contributor

In the current design, the crashd programmatic API relies completely on built-in functions defined in the project. However, as a user of the crashd API, it would be nice to be able to inject custom Starlark functions that are defined using Go.

Design

When using Crashd as a programmatic API, a developer should be able to define custom built-in Starlark functions and be able to use that function in scripts. For instance, suppose I want to define a custom function, called repeat, that prints a value N times, as shown:

repeat(value="Hello", count=2)

The previous function is not part of the core Crashd functions, however, the Crashd API should provide a way to inject a Go definition, for that function, so that it can be invoked in Crashd scripts.

Define custom function in Go

func repeatFunc(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
	var value string
        var count int
	if err := starlark.UnpackArgs(
		"repeat", args, kwargs,
		"value", &value,
		"count", &count,
	); err != nil {
		return starlark.None, fmt.Errorf("%s: %s", "repeat", err)
	}

	for (i :=0; i < count; i++){fmt.Println(value)}
      
	return starlark.None, nil
}

Register custom func with Crashd

Next, the Crashd API should provide a way to register the function prior to launching. For instance, the snippet below shows how someone, using the crashd API, would programmatically launch crashd and inject custom function to be made available to executing scripts:

import "github.com/vmware-tanzu/crash-diagnostics/exec"
func main() {
    script := "some/path/script.star"
    exec.NewWithBuiltins(script, exec.StarlarkBuiltin{"repeat",repeatFunc}).Run()
}

Where

  • NewWithBuiltins is defined as func NewWithBuiltins(scriptfile string, StarlarkBuiltin...)
  • StarlarkBuiltin is defined as
type StarlarkBuiltin{
    Name string
    Builtin func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant