Skip to content

Commit 4c48902

Browse files
committed
[v3] Add validator. Write the skaffold validation rule to Kptfile pipeline.
1 parent d460b68 commit 4c48902

File tree

4 files changed

+246
-17
lines changed

4 files changed

+246
-17
lines changed

pkg/skaffold/render/renderer/renderer.go

+39-5
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"context"
2020
"fmt"
2121
"io"
22+
"io/ioutil"
2223
"os"
2324
"os/exec"
2425
"path/filepath"
@@ -30,6 +31,7 @@ import (
3031
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/manifest"
3132
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/render/generate"
3233
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/render/kptfile"
34+
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/render/validate"
3335
latestV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v2"
3436
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/util"
3537
)
@@ -44,17 +46,37 @@ type Renderer interface {
4446
}
4547

4648
// NewSkaffoldRenderer creates a new Renderer object from the latestV2 API schema.
47-
func NewSkaffoldRenderer(config *latestV2.RenderConfig, workingDir string) Renderer {
49+
func NewSkaffoldRenderer(config *latestV2.RenderConfig, workingDir string) (Renderer, error) {
4850
// TODO(yuwenma): return instance of kpt-managed mode or skaffold-managed mode defer to the config.Path fields.
4951
// The alpha implementation only has skaffold-managed mode.
5052
// TODO(yuwenma): The current work directory may not be accurate if users use --filepath flag.
5153
hydrationDir := filepath.Join(workingDir, DefaultHydrationDir)
52-
generator := generate.NewGenerator(workingDir, *config.Generate)
53-
return &SkaffoldRenderer{Generator: *generator, workingDir: workingDir, hydrationDir: hydrationDir}
54+
55+
var generator *generate.Generator
56+
if config.Generate == nil {
57+
// If render.generate is not given, default to current working directory.
58+
defaultManifests := filepath.Join(workingDir, "*.yaml")
59+
generator = generate.NewGenerator(workingDir, latestV2.Generate{Manifests: []string{defaultManifests}})
60+
} else {
61+
generator = generate.NewGenerator(workingDir, *config.Generate)
62+
}
63+
64+
var validator *validate.Validator
65+
if config.Validate != nil {
66+
var err error
67+
validator, err = validate.NewValidator(*config.Validate)
68+
if err != nil {
69+
return nil, err
70+
}
71+
} else {
72+
validator, _ = validate.NewValidator([]latestV2.Validator{})
73+
}
74+
return &SkaffoldRenderer{Generator: *generator, Validator: *validator, workingDir: workingDir, hydrationDir: hydrationDir}, nil
5475
}
5576

5677
type SkaffoldRenderer struct {
5778
generate.Generator
79+
validate.Validator
5880
workingDir string
5981
hydrationDir string
6082
labels map[string]string
@@ -111,10 +133,22 @@ func (r *SkaffoldRenderer) Render(ctx context.Context, out io.Writer, builds []g
111133
defer file.Close()
112134
kfConfig := &kptfile.KptFile{}
113135
if err := yaml.NewDecoder(file).Decode(&kfConfig); err != nil {
114-
return err
136+
return fmt.Errorf("unable to parse %v\n, please check if the kptfile is updated to new apiVersion > v1alpha2",
137+
kptFilePath)
138+
}
139+
if kfConfig.Pipeline == nil {
140+
kfConfig.Pipeline = &kptfile.Pipeline{}
115141
}
116142

117-
// TODO: Update the Kptfile with the new validators.
143+
kfConfig.Pipeline.Validators = r.GetDeclarativeValidators()
118144
// TODO: Update the Kptfile with the new mutators.
145+
146+
configByte, err := yaml.Marshal(kfConfig)
147+
if err != nil {
148+
return fmt.Errorf("unable to update %v", kptFilePath)
149+
}
150+
if err = ioutil.WriteFile(kptFilePath, configByte, 0644); err != nil {
151+
return fmt.Errorf("unable to update %v", kptFilePath)
152+
}
119153
return nil
120154
}

pkg/skaffold/render/renderer/renderer_test.go

+97-12
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,13 @@ limitations under the License.
1616
package renderer
1717

1818
import (
19+
"bytes"
20+
"context"
1921
"fmt"
2022
"path/filepath"
2123
"testing"
2224

25+
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph"
2326
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/render/kptfile"
2427
latestV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v2"
2528
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/util"
@@ -54,17 +57,99 @@ metadata:
5457
`
5558
)
5659

57-
func TestRender_StoredInCache(t *testing.T) {
58-
testutil.Run(t, "", func(t *testutil.T) {
59-
r := NewSkaffoldRenderer(&latestV2.RenderConfig{Generate: &latestV2.Generate{
60-
Manifests: []string{"pod.yaml"}}}, "")
61-
fakeCmd := testutil.CmdRunOut(fmt.Sprintf("kpt pkg init %v", DefaultHydrationDir), "")
62-
t.Override(&util.DefaultExecCommand, fakeCmd)
63-
t.NewTempDir().
64-
Write("pod.yaml", podYaml).
65-
Write(filepath.Join(DefaultHydrationDir, kptfile.KptFileName), initKptfile).
66-
Touch("empty.ignored").
67-
Chdir()
60+
func TestRender(t *testing.T) {
61+
tests := []struct {
62+
description string
63+
renderConfig *latestV2.RenderConfig
64+
originalKptfile string
65+
updatedKptfile string
66+
}{
67+
{
68+
description: "single manifests, no hydration rule",
69+
renderConfig: &latestV2.RenderConfig{
70+
Generate: &latestV2.Generate{Manifests: []string{"pod.yaml"}},
71+
},
72+
originalKptfile: initKptfile,
73+
updatedKptfile: `apiVersion: kpt.dev/v1alpha2
74+
kind: Kptfile
75+
metadata:
76+
name: skaffold
77+
pipeline: {}
78+
`,
79+
},
80+
81+
{
82+
description: "manifests not given.",
83+
renderConfig: &latestV2.RenderConfig{},
84+
originalKptfile: initKptfile,
85+
updatedKptfile: `apiVersion: kpt.dev/v1alpha2
86+
kind: Kptfile
87+
metadata:
88+
name: skaffold
89+
pipeline: {}
90+
`,
91+
},
92+
{
93+
description: "single manifests with validation rule.",
94+
renderConfig: &latestV2.RenderConfig{
95+
Generate: &latestV2.Generate{Manifests: []string{"pod.yaml"}},
96+
Validate: &[]latestV2.Validator{
97+
latestV2.Validator{Name: "kubeval"},
98+
},
99+
},
100+
originalKptfile: initKptfile,
101+
updatedKptfile: `apiVersion: kpt.dev/v1alpha2
102+
kind: Kptfile
103+
metadata:
104+
name: skaffold
105+
pipeline:
106+
validators:
107+
- image: gcr.io/kpt-fn/kubeval:v0.1
108+
`,
109+
},
110+
{
111+
description: "Validation rule needs to be updated.",
112+
renderConfig: &latestV2.RenderConfig{
113+
Generate: &latestV2.Generate{Manifests: []string{"pod.yaml"}},
114+
Validate: &[]latestV2.Validator{
115+
latestV2.Validator{Name: "kubeval"},
116+
},
117+
},
118+
originalKptfile: `apiVersion: kpt.dev/v1alpha2
119+
kind: Kptfile
120+
metadata:
121+
name: skaffold
122+
pipeline:
123+
validators:
124+
- image: gcr.io/kpt-fn/SOME-OTHER-FUNC
125+
`,
126+
updatedKptfile: `apiVersion: kpt.dev/v1alpha2
127+
kind: Kptfile
128+
metadata:
129+
name: skaffold
130+
pipeline:
131+
validators:
132+
- image: gcr.io/kpt-fn/kubeval:v0.1
133+
`,
134+
},
68135
}
136+
for _, test := range tests {
137+
testutil.Run(t, test.description, func(t *testutil.T) {
138+
r, err := NewSkaffoldRenderer(test.renderConfig, "")
139+
t.CheckNoError(err)
140+
fakeCmd := testutil.CmdRunOut(fmt.Sprintf("kpt pkg init %v", DefaultHydrationDir), "")
141+
t.Override(&util.DefaultExecCommand, fakeCmd)
142+
t.NewTempDir().
143+
Write("pod.yaml", podYaml).
144+
Write(filepath.Join(DefaultHydrationDir, kptfile.KptFileName), test.originalKptfile).
145+
Touch("empty.ignored").
146+
Chdir()
69147

70-
}
148+
var b bytes.Buffer
149+
err = r.Render(context.Background(), &b, []graph.Artifact{{ImageName: "leeroy-web", Tag: "leeroy-web:v1"}})
150+
t.CheckNoError(err)
151+
t.CheckFileExistAndContent(filepath.Join(DefaultHydrationDir, dryFileName), []byte(labeledPodYaml))
152+
t.CheckFileExistAndContent(filepath.Join(DefaultHydrationDir, kptfile.KptFileName), []byte(test.updatedKptfile))
153+
})
154+
}
155+
}
+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
Copyright 2021 The Skaffold Authors
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
package validate
17+
18+
import (
19+
"fmt"
20+
21+
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/render/kptfile"
22+
latestV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v2"
23+
)
24+
25+
var ValidatorWhitelist = map[string]kptfile.Function{
26+
"kubeval": kptfile.Function{
27+
Image: "gcr.io/kpt-fn/kubeval:v0.1",
28+
},
29+
// TODO: Add conftest validator in kpt catalog.
30+
}
31+
32+
// NewValidator instantiates a Validator object.
33+
func NewValidator(config []latestV2.Validator) (*Validator, error) {
34+
var fns []kptfile.Function
35+
for _, c := range config {
36+
fn, ok := ValidatorWhitelist[c.Name]
37+
if !ok {
38+
return nil, fmt.Errorf("unsupported validator %v", c.Name)
39+
}
40+
fns = append(fns, fn)
41+
}
42+
return &Validator{kptFn: fns}, nil
43+
}
44+
45+
type Validator struct {
46+
kptFn []kptfile.Function
47+
}
48+
49+
// GetDeclarativeValidators transforms and returns the skaffold validators defined in skaffold.yaml
50+
func (v *Validator) GetDeclarativeValidators() []kptfile.Function {
51+
// TODO: guarantee the v.kptFn is updated once users changed skaffold.yaml file.
52+
return v.kptFn
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Copyright 2021 The Skaffold Authors
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
package validate
17+
18+
import (
19+
"testing"
20+
21+
latestV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v2"
22+
"github.com/GoogleContainerTools/skaffold/testutil"
23+
)
24+
25+
func TestValidatorInit(t *testing.T) {
26+
tests := []struct {
27+
description string
28+
config []latestV2.Validator
29+
shouldErr bool
30+
}{
31+
{
32+
description: "no validation",
33+
config: []latestV2.Validator{},
34+
shouldErr: false,
35+
},
36+
{
37+
description: "kubeval validator",
38+
config: []latestV2.Validator{
39+
latestV2.Validator{Name: "kubeval"},
40+
},
41+
shouldErr: false,
42+
},
43+
{
44+
description: "invalid validator",
45+
config: []latestV2.Validator{
46+
latestV2.Validator{Name: "bad-validator"},
47+
},
48+
shouldErr: true,
49+
},
50+
}
51+
for _, test := range tests {
52+
testutil.Run(t, test.description, func(t *testutil.T) {
53+
_, err := NewValidator(test.config)
54+
t.CheckError(test.shouldErr, err)
55+
})
56+
}
57+
}

0 commit comments

Comments
 (0)