Skip to content
Open
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
12 changes: 12 additions & 0 deletions api/generated/applyconfigurations/kptfile/v1/function.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions api/kptfile/v1/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,11 @@ type Function struct {
// - Check resource count among the selected resources:
// `when: "resources.filter(r, r.kind == 'Deployment').size() > 0"`
CelCondition string `yaml:"when,omitempty" json:"when,omitempty"`

// Timeout specifies the maximum execution time for this function step
// (e.g. "30s", "1m", "5m"). If omitted, the default function timeout (5m)
// is used.
Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would propose using metav1.Duration for this as it already has proper unmarshalling, but that would require pulling in apimachinery...

Do we want to maybe have a copy of that metav1.Duration type somewhere so we can use it here (and elsewhere later) @kptdev/maintainers?

}

// ResourceReference identifies a resource within the package by its API identity.
Expand Down
27 changes: 27 additions & 0 deletions api/kptfile/v1/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"regexp"
"slices"
"strings"
"time"

"github.com/distribution/reference"
"sigs.k8s.io/kustomize/kyaml/filesys"
Expand Down Expand Up @@ -256,6 +257,32 @@ func (f *Function) validate(fsys filesys.FileSystem, fnType string, idx int, pkg
if err := f.validateExecutor(fnType, idx); err != nil {
return err
}
if err := f.validateTimeout(fnType, idx); err != nil {
return err
}
return nil
}

// validateTimeout checks that the optional timeout string is a valid positive duration.
func (f *Function) validateTimeout(fnType string, idx int) error {
if f.Timeout == "" {
return nil
}
d, err := time.ParseDuration(f.Timeout)
if err != nil {
return &ValidateError{
Field: fmt.Sprintf("pipeline.%s[%d].timeout", fnType, idx),
Value: f.Timeout,
Reason: fmt.Sprintf("invalid duration %q: %v", f.Timeout, err),
}
}
if d <= 0 {
return &ValidateError{
Field: fmt.Sprintf("pipeline.%s[%d].timeout", fnType, idx),
Value: f.Timeout,
Reason: fmt.Sprintf("timeout %q must be greater than zero", f.Timeout),
}
}
return nil
}

Expand Down
70 changes: 70 additions & 0 deletions api/kptfile/v1/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,76 @@ func TestKptfileValidate(t *testing.T) {
},
valid: false,
},
{
name: "pipeline: valid mutator step timeout",
kptfile: KptFile{
Pipeline: &Pipeline{
Mutators: []Function{
{
Image: "image",
Timeout: "30s",
},
},
},
},
valid: true,
},
{
name: "pipeline: valid validator step timeout",
kptfile: KptFile{
Pipeline: &Pipeline{
Validators: []Function{
{
Image: "image",
Timeout: "1m",
},
},
},
},
valid: true,
},
{
name: "pipeline: invalid step timeout syntax",
kptfile: KptFile{
Pipeline: &Pipeline{
Mutators: []Function{
{
Image: "image",
Timeout: "not-a-duration",
},
},
},
},
valid: false,
},
{
name: "pipeline: non-positive zero step timeout",
kptfile: KptFile{
Pipeline: &Pipeline{
Mutators: []Function{
{
Image: "image",
Timeout: "0s",
},
},
},
},
valid: false,
},
{
name: "pipeline: negative step timeout",
kptfile: KptFile{
Pipeline: &Pipeline{
Validators: []Function{
{
Image: "image",
Timeout: "-10s",
},
},
},
},
valid: false,
},
}

for _, c := range cases {
Expand Down
4 changes: 2 additions & 2 deletions cli/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ module github.com/kptdev/kpt/cli
go 1.26.9

// TODO: Comment the lines below out when the next version of the API is released.
// replace github.com/kptdev/kpt/api => ../api
// replace github.com/kptdev/kpt => ..
replace github.com/kptdev/kpt/api => ../api
replace github.com/kptdev/kpt => ..

require (
github.com/go-errors/errors v1.5.1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@
"type": "string",
"x-go-name": "Tag"
},
"timeout": {
"description": "`Timeout` is an optional field for specifying the maximum time the function is allowed to run,\ne.g. '30s' or '10m'. If omitted, the function is limited by the pipeline run timeout (if set)\nor defaults to 5 minutes. Applicable to container and exec based functions only.",
"type": "string",
"x-go-name": "Timeout"
},
"when": {
"description": "CelCondition is an optional CEL expression (exposed as 'when' in YAML) that determines whether this\nfunction should be executed. The expression is evaluated against the list\nof KRM resources passed to this function step (after `Selectors` and\n`Exclude` have been applied) and should return a boolean value.\nIf omitted or evaluates to true, the function executes normally.\nIf evaluates to false, the function is skipped.\n\nExamples:\n\nCheck if a specific ConfigMap exists among the selected resources:\nwhen: `\"resources.exists(r, r.kind == 'ConfigMap' && r.metadata.name == 'my-config')\"`\n\nCheck resource count among the selected resources:\n`when: \"resources.filter(r, r.kind == 'Deployment').size() > 0\"`",
"type": "string",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,13 @@ definitions:
Can be a semver constraint satisfying this spec: https://github.com/Masterminds/semver?tab=readme-ov-file#checking-version-constraints
type: string
x-go-name: Tag
timeout:
description: |-
`Timeout` is an optional field for specifying the maximum time the function is allowed to run,
e.g. '30s' or '10m'. If omitted, the function is limited by the pipeline run timeout (if set)
or defaults to 5 minutes. Applicable to container and exec based functions only.
type: string
x-go-name: Timeout
when:
description: |-
CelCondition is an optional CEL expression (exposed as 'when' in YAML) that determines whether this
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/kptdev/kpt
go 1.26.9

// TODO: Comment the line below out when the next version of the API is released.
// replace github.com/kptdev/kpt/api => ./api
replace github.com/kptdev/kpt/api => ./api

require (
github.com/Masterminds/semver/v3 v3.5.0
Expand Down
11 changes: 11 additions & 0 deletions pkg/fn/runtime/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,15 @@ func NewRunner(
pkgCtxGenerator := &builtins.PackageContextGenerator{}
fltr.Run = pkgCtxGenerator.Run
} else {
var fnTimeout time.Duration
if f.Timeout != "" {
var err error
fnTimeout, err = time.ParseDuration(f.Timeout)
if err != nil {
return nil, fmt.Errorf("invalid function timeout %q: %w", f.Timeout, err)
}
}

switch {
case f.Image != "":
// If allowWasm is true, we will use wasm runtime for image field.
Expand All @@ -145,6 +154,7 @@ func NewRunner(
cfn := &ContainerFn{
Image: f.Image,
ImagePullPolicy: opts.ImagePullPolicy,
Timeout: fnTimeout,
Perm: ContainerFnPermission{
AllowNetwork: opts.AllowNetwork,
// mounts are disabled for render operations (currently)
Expand Down Expand Up @@ -181,6 +191,7 @@ func NewRunner(
eFn := &ExecFn{
Path: execPath,
Args: execArgs,
Timeout: fnTimeout,
FnResult: fnResult,
}
fltr.Run = eFn.Run
Expand Down
34 changes: 33 additions & 1 deletion pkg/fn/runtime/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ import (
"context"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"

fnresultv1 "github.com/kptdev/kpt/api/fnresult/v1"
kptfilev1 "github.com/kptdev/kpt/api/kptfile/v1"
Expand Down Expand Up @@ -1123,7 +1125,6 @@ func TestPrintFnResult(t *testing.T) {
})
}
}

// TestFunctionRunner_do_AcceptsNamelessList: a nameless *List-kind
// resource (e.g. ConfigMapList) must pass do()'s validation on both
// the input and output side, matching krmvalidate.IsKRM's exemption
Expand Down Expand Up @@ -1155,3 +1156,34 @@ items: []
_, err = fr.do(nodes)
assert.NoError(t, err, "a nameless *List resource must not be rejected as non-KRM")
}

func TestNewRunner_StepTimeout(t *testing.T) {
if _, err := exec.LookPath("sleep"); err != nil {
t.Skip("skipping exec timeout test: no sleep binary found")
}

out := &bytes.Buffer{}
ctx := printer.WithContext(context.Background(), printer.New(out, out))
opts := runneroptions.RunnerOptions{}
opts.InitDefaults(runneroptions.GHCRImagePrefix)

fnResults := fnresultv1.NewResultList()
fr, err := NewRunner(ctx, filesys.MakeFsInMemory(), &kptfilev1.Function{Exec: "sleep 30", Timeout: "100ms"},
"", fnResults, opts, nil)
require.NoError(t, err)

start := time.Now()
_, err = fr.Filter(nil)
assert.Error(t, err)
assert.Less(t, time.Since(start), 5*time.Second)
require.Len(t, fnResults.Items, 1)
}

func TestNewRunner_InvalidTimeout(t *testing.T) {
opts := runneroptions.RunnerOptions{}
opts.InitDefaults(runneroptions.GHCRImagePrefix)
fnResults := fnresultv1.NewResultList()
_, err := NewRunner(context.Background(), filesys.MakeFsInMemory(), &kptfilev1.Function{Exec: "sleep 30", Timeout: "not-a-duration"},
"", fnResults, opts, nil)
assert.ErrorContains(t, err, "invalid function timeout \"not-a-duration\"")
}
42 changes: 42 additions & 0 deletions pkg/lib/kptops/render_executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ import (
"bytes"
"context"
"fmt"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"

fnresultv1 "github.com/kptdev/kpt/api/fnresult/v1"
kptfilev1 "github.com/kptdev/kpt/api/kptfile/v1"
Expand Down Expand Up @@ -397,6 +399,46 @@ func TestRenderer_Execute_RenderOrder(t *testing.T) {
})
}
}
func TestRenderer_Execute_StepTimeout(t *testing.T) {
if _, err := exec.LookPath("sleep"); err != nil {
t.Skip("skipping render timeout test: no sleep binary found")
}

var outputBuffer bytes.Buffer
ctx := printer.WithContext(t.Context(), printer.New(&outputBuffer, &outputBuffer))

mockFileSystem := filesys.MakeFsInMemory()
assert.NoError(t, mockFileSystem.Mkdir(rootString))
assert.NoError(t, mockFileSystem.WriteFile(filepath.Join(rootString, "Kptfile"), []byte(`apiVersion: kpt.dev/v1
kind: Kptfile
metadata:
name: root-package
pipeline:
mutators:
- exec: sleep 30
timeout: 100ms
`)))
assert.NoError(t, mockFileSystem.WriteFile(filepath.Join(rootString, "resources.yaml"), []byte(`apiVersion: v1
kind: ConfigMap
metadata:
name: root-cm
`)))

opts := runneroptions.RunnerOptions{}
opts.InitDefaults(runneroptions.GHCRImagePrefix)
opts.AllowExec = true
renderer := &Renderer{
PkgPath: rootString,
FileSystem: mockFileSystem,
RunnerOptions: opts,
Output: &bytes.Buffer{},
}

start := time.Now()
_, err := renderer.Execute(ctx)
assert.Error(t, err)
assert.Less(t, time.Since(start), 10*time.Second)
}
func TestRunPipeline_SubpkgNameDisplay(t *testing.T) {
tests := []struct {
name string
Expand Down
Loading