-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
skaffoldyamls.go
239 lines (226 loc) · 7.89 KB
/
skaffoldyamls.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/*
Copyright 2021 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package lint
import (
"context"
"fmt"
"path/filepath"
"strconv"
"strings"
"github.com/google/uuid"
"go.lsp.dev/protocol"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/kubectl/pkg/scheme"
"sigs.k8s.io/kustomize/kyaml/yaml"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/config"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/kubernetes/debugging"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/output/log"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/parser"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/util"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/version"
)
// for testing
var skaffoldYamlRules = &skaffoldYamlLintRules
var getConfigSet = parser.GetConfigSet
var SkaffoldYamlLinters = []Linter{
&YamlFieldLinter{},
}
type skaffoldYamlUseStaticPortTemplate struct {
ResourceType string
ResourceName string
Port string
LocalPort string
}
var skaffoldYamlLintRules = []Rule{
{
RuleID: SkaffoldYamlAPIVersionOutOfDate,
RuleType: YamlFieldLintRule,
Severity: protocol.DiagnosticSeverityWarning,
Filter: YamlFieldFilter{
Filter: yaml.FieldMatcher{Name: "apiVersion", StringRegexValue: fmt.Sprintf("[^%s]", version.Get().ConfigVersion)},
},
ExplanationTemplate: fmt.Sprintf("Found 'apiVersion' field with value that is not the latest skaffold apiVersion. Modify the apiVersion to the latest version: `apiVersion: %s` "+
"or run the 'skaffold fix' command to have skaffold upgrade this for you.", version.Get().ConfigVersion),
},
{
RuleID: SkaffoldYamlUseStaticPort,
RuleType: YamlFieldLintRule,
Severity: protocol.DiagnosticSeverityWarning,
Filter: YamlFieldFilter{
Filter: yaml.FieldMatcher{Name: "portForward"},
InvertMatch: true,
},
ExplanationTemplate: "It is a skaffold best practice to specify a static port (vs skaffold dynamically choosing one) for port forwarding " +
"container based resources skaffold deploys. This is helpful because with this the local ports are predictable across dev sessions which " +
" makes testing/debugging easier. It is recommended to add the following stanza at the end of your skaffold.yaml for each shown deployed resource:\n" +
`portForward:{{range $k,$v := .FieldMap }}
- resourceType: {{ $v.ResourceType }}
resourceName: {{ $v.ResourceName }}
port: {{ $v.Port }}
localPort: {{ $v.LocalPort }}{{end}}`,
LintConditions: []func(InputParams) bool{
func(params InputParams) bool {
// checks if manifests stanza exists
linter := &YamlFieldLinter{}
recs, err := linter.Lint(params, &[]Rule{
{
RuleType: YamlFieldLintRule,
Filter: YamlFieldFilter{
Filter: yaml.Lookup("manifests"),
},
},
})
if err != nil {
log.Entry(context.TODO()).Debugf("lint condition for rule %s encontered error: %v", SkaffoldYamlUseStaticPort, err)
return false
}
if len(*recs) > 0 {
return true
}
return false
},
},
ExplanationPopulator: func(lintInputs InputParams) (explanationInfo, error) {
fieldMap := map[string]interface{}{}
forwardedPorts := util.PortSet{}
for _, pattern := range lintInputs.SkaffoldConfig.Render.Generate.RawK8s {
// NOTE: pattern is a pattern that can have wildcards, eg: leeroy-app/kubernetes/*
if util.IsURL(pattern) {
log.Entry(context.TODO()).Infof("skaffold lint found url manifest when processing rule %d and is skipping lint rules for: %s", SkaffoldYamlUseStaticPort, pattern)
continue
}
// filepaths are all absolute from config parsing step via tags.MakeFilePathsAbsolute
expanded, err := filepath.Glob(pattern)
if err != nil {
return explanationInfo{}, err
}
for _, relPath := range expanded {
b, err := util.ReadFile(relPath)
if err != nil {
return explanationInfo{}, err
}
decoder := scheme.Codecs.UniversalDeserializer()
for _, resourceYAML := range strings.Split(string(b), "---") {
// skip empty documents, `Decode` will fail on them
if len(resourceYAML) == 0 {
continue
}
obj, _, err := decoder.Decode([]byte(resourceYAML), nil, nil)
if err != nil {
return explanationInfo{}, err
}
suggestionTemplates := parseManifestUseStaticPortSuggestion(obj)
for _, tmplt := range suggestionTemplates {
localPort := util.GetAvailablePort(util.Loopback, 32581, &forwardedPorts)
forwardedPorts.Set(localPort)
tmplt.ResourceType = strings.ToLower(tmplt.ResourceType)
tmplt.LocalPort = strconv.Itoa(localPort)
fieldMap[uuid.NewString()] = tmplt
}
}
}
}
return explanationInfo{fieldMap}, nil
},
},
}
func GetSkaffoldYamlsLintResults(ctx context.Context, opts Options) (*[]Result, error) {
cfgs, err := getConfigSet(ctx, config.SkaffoldOptions{
ConfigurationFile: opts.Filename,
ConfigurationFilter: opts.Modules,
RemoteCacheDir: opts.RemoteCacheDir,
Profiles: opts.Profiles,
})
if err != nil {
return nil, err
}
workdir, err := realWorkDir()
if err != nil {
return nil, err
}
l := []Result{}
for _, c := range cfgs {
b, err := util.ReadFile(c.SourceFile)
if err != nil {
return nil, err
}
skaffoldyaml := ConfigFile{
AbsPath: c.SourceFile,
RelPath: strings.TrimPrefix(c.SourceFile, workdir),
Text: string(b),
}
for _, r := range SkaffoldYamlLinters {
recs, err := r.Lint(InputParams{
ConfigFile: skaffoldyaml,
SkaffoldConfig: c,
}, skaffoldYamlRules)
if err != nil {
return nil, err
}
l = append(l, *recs...)
}
}
return &l, nil
}
func parseManifestUseStaticPortSuggestion(obj runtime.Object) []skaffoldYamlUseStaticPortTemplate {
out := []skaffoldYamlUseStaticPortTemplate{}
switch o := obj.(type) {
case *v1.Pod:
for i := range o.Spec.Containers {
for j := range o.Spec.Containers[i].Ports {
out = append(out, skaffoldYamlUseStaticPortTemplate{
ResourceType: o.GroupVersionKind().Kind,
ResourceName: o.Name,
Port: strconv.Itoa(int(o.Spec.Containers[i].Ports[j].ContainerPort)),
})
}
}
case *v1.PodList:
for _, item := range o.Items {
for i := range item.Spec.Containers {
for j := range item.Spec.Containers[i].Ports {
out = append(out, skaffoldYamlUseStaticPortTemplate{
ResourceType: item.GroupVersionKind().Kind,
ResourceName: item.Name,
Port: strconv.Itoa(int(item.Spec.Containers[i].Ports[j].ContainerPort)),
})
}
}
}
case *appsv1.Deployment:
for i := range o.Spec.Template.Spec.Containers {
for j := range o.Spec.Template.Spec.Containers[i].Ports {
out = append(out, skaffoldYamlUseStaticPortTemplate{
ResourceType: o.GroupVersionKind().Kind,
ResourceName: o.Name,
Port: strconv.Itoa(int(o.Spec.Template.Spec.Containers[i].Ports[j].ContainerPort)),
})
}
}
default:
group, version, _, description := debugging.Describe(obj)
if group == "apps" || group == "batch" {
if version != "v1" {
// treat deprecated objects as errors
log.Entry(context.Background()).Errorf("deprecated versions not supported by skaffold lint: %s (%s)", description, version)
} else {
log.Entry(context.Background()).Warnf("no skaffold lint parsing for: %s", description)
}
} else {
log.Entry(context.Background()).Debugf("no skaffold lint parsing for: %s", description)
}
}
return out
}