-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
context.go
455 lines (396 loc) · 17.2 KB
/
context.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*
Copyright 2019 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 runcontext
import (
"context"
"fmt"
"os"
"os/exec"
"strings"
"github.com/google/uuid"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/config"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/constants"
kubectx "github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/kubernetes/context"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/output/log"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/schema/latest"
schemaUtil "github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/schema/util"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/util"
)
type RunContext struct {
Opts config.SkaffoldOptions
Pipelines Pipelines
KubeContext string
Namespaces []string
WorkingDir string
InsecureRegistries map[string]bool
Cluster config.Cluster
RunID string
}
// Pipelines encapsulates multiple config pipelines
type Pipelines struct {
pipelines []latest.Pipeline
pipelinesByConfig map[string]latest.Pipeline
pipelinesByImageName map[string]latest.Pipeline
orderedConfigs []string
}
// All returns all config pipelines.
func (ps Pipelines) All() []latest.Pipeline {
return ps.pipelines
}
// Returns the config names in the correct dependency order to be mapped against their proper pipeline.
func (ps Pipelines) AllOrderedConfigNames() []string {
return ps.orderedConfigs
}
// Returns a pipeline given its associated config name.
func (ps Pipelines) GetForConfigName(configName string) latest.Pipeline {
return ps.pipelinesByConfig[configName]
}
// Head returns the first `latest.Pipeline`.
func (ps Pipelines) Head() latest.Pipeline {
return ps.pipelines[0] // there always exists atleast one pipeline.
}
// Select returns the first `latest.Pipeline` that matches the given artifact `imageName`.
func (ps Pipelines) Select(imageName string) (latest.Pipeline, bool) {
p, found := ps.pipelinesByImageName[imageName]
return p, found
}
// IsMultiPipeline returns true if there are more than one constituent skaffold pipelines.
func (ps Pipelines) IsMultiPipeline() bool {
return len(ps.pipelines) > 1
}
// IsMultiPipeline returns true if there are more than one target kubernetes clusters.
func (ps Pipelines) IsMultiCluster() bool {
var k string
for _, p := range ps.pipelines {
if p.Deploy.KubeContext == "" {
continue
}
if k == "" {
k = p.Deploy.KubeContext
} else if k != p.Deploy.KubeContext {
return true
}
}
return false
}
func (ps Pipelines) PortForwardResources() []*latest.PortForwardResource {
var pf []*latest.PortForwardResource
for _, p := range ps.pipelines {
pf = append(pf, p.PortForward...)
}
return pf
}
func (ps Pipelines) Artifacts() []*latest.Artifact {
var artifacts []*latest.Artifact
for _, p := range ps.pipelines {
artifacts = append(artifacts, p.Build.Artifacts...)
}
return artifacts
}
// TODO: Clean up code duplication
func (ps Pipelines) DeployConfigs() []latest.DeployConfig {
var cfgs []latest.DeployConfig
for _, p := range ps.pipelines {
cfgs = append(cfgs, p.Deploy)
}
return cfgs
}
func (ps Pipelines) Deployers() []latest.DeployConfig {
var deployers []latest.DeployConfig
for _, p := range ps.pipelines {
deployers = append(deployers, p.Deploy)
}
return deployers
}
func (ps Pipelines) Renderers() []latest.RenderConfig {
var rcs []latest.RenderConfig
for _, p := range ps.pipelines {
rcs = append(rcs, p.Render)
}
return rcs
}
func (ps Pipelines) TestCases() []*latest.TestCase {
var tests []*latest.TestCase
for _, p := range ps.pipelines {
tests = append(tests, p.Test...)
}
return tests
}
// TransformAllowList returns combined allowlist from pipelines
func (ps Pipelines) TransformAllowList() []latest.ResourceFilter {
var allowlist []latest.ResourceFilter
for _, p := range ps.pipelines {
if p.ResourceSelector.Allow != nil {
allowlist = append(allowlist, p.ResourceSelector.Allow...)
}
}
return allowlist
}
// TransformDenyList returns combined denylist from pipelines
func (ps Pipelines) TransformDenyList() []latest.ResourceFilter {
var denylist []latest.ResourceFilter
for _, p := range ps.pipelines {
if p.ResourceSelector.Deny != nil {
denylist = append(denylist, p.ResourceSelector.Deny...)
}
}
return denylist
}
func (ps Pipelines) StatusCheckTolerateFailures() bool {
failureTolerance := false
// set the group status check deadline to maximum of any individually specified value
for _, p := range ps.pipelines {
if p.Deploy.TolerateFailuresUntilDeadline {
failureTolerance = true
}
}
return failureTolerance
}
func (ps Pipelines) StatusCheckDeadlineSeconds() int {
c := 0
// set the group status check deadline to maximum of any individually specified value
for _, p := range ps.pipelines {
if p.Deploy.StatusCheckDeadlineSeconds > c {
c = p.Deploy.StatusCheckDeadlineSeconds
}
}
return c
}
func NewPipelines(pipelinesByConfig map[string]latest.Pipeline, orderedConfigs []string) Pipelines {
m := make(map[string]latest.Pipeline)
var pipelines []latest.Pipeline
for _, cfgName := range orderedConfigs {
p := pipelinesByConfig[cfgName]
for _, a := range p.Build.Artifacts {
m[a.ImageName] = p
}
pipelines = append(pipelines, p)
}
return Pipelines{pipelines: pipelines, pipelinesByImageName: m, pipelinesByConfig: pipelinesByConfig, orderedConfigs: orderedConfigs}
}
func (rc *RunContext) PipelineForImage(imageName string) (latest.Pipeline, bool) {
return rc.Pipelines.Select(imageName)
}
func (rc *RunContext) PortForwardResources() []*latest.PortForwardResource {
return rc.Pipelines.PortForwardResources()
}
func (rc *RunContext) Artifacts() []*latest.Artifact { return rc.Pipelines.Artifacts() }
func (rc *RunContext) DeployConfigs() []latest.DeployConfig { return rc.Pipelines.DeployConfigs() }
func (rc *RunContext) Deployers() []latest.DeployConfig { return rc.Pipelines.Deployers() }
func (rc *RunContext) Renderers() []latest.RenderConfig { return rc.Pipelines.Renderers() }
func (rc *RunContext) TestCases() []*latest.TestCase { return rc.Pipelines.TestCases() }
func (rc *RunContext) StatusCheckDeadlineSeconds() int {
return rc.Pipelines.StatusCheckDeadlineSeconds()
}
func (rc *RunContext) StatusCheckTolerateFailures() bool {
return rc.Opts.TolerateFailuresStatusCheck || rc.Pipelines.StatusCheckTolerateFailures()
}
func (rc *RunContext) StatusCheckCRDsFile() string {
return rc.Opts.StatusCheckSelectorsFile
}
func (rc *RunContext) SkipTests() bool {
return rc.Opts.SkipTests
}
func (rc *RunContext) IsTestPhaseActive() bool {
return !rc.SkipTests() && len(rc.TestCases()) != 0
}
func (rc *RunContext) TransformAllowList() []latest.ResourceFilter {
return rc.Pipelines.TransformAllowList()
}
func (rc *RunContext) TransformDenyList() []latest.ResourceFilter {
return rc.Pipelines.TransformDenyList()
}
// AddSkaffoldLabels tells the Runner whether to add skaffold-specific labels.
// We only ever skip adding labels during a `skaffold render`.
func (rc *RunContext) AddSkaffoldLabels() bool {
return rc.Opts.Mode() != config.RunModes.Render
}
func (rc *RunContext) UsingLegacyHelmDeploy() bool {
for _, config := range rc.DeployConfigs() {
if config.LegacyHelmDeploy != nil {
return true
}
}
return false
}
func (rc *RunContext) DefaultPipeline() latest.Pipeline { return rc.Pipelines.Head() }
func (rc *RunContext) GetKubeContext() string { return rc.KubeContext }
func (rc *RunContext) GetNamespaces() []string { return rc.Namespaces }
func (rc *RunContext) GetPipelines() []latest.Pipeline { return rc.Pipelines.All() }
func (rc *RunContext) GetInsecureRegistries() map[string]bool { return rc.InsecureRegistries }
func (rc *RunContext) GetWorkingDir() string { return rc.WorkingDir }
func (rc *RunContext) GetCluster() config.Cluster { return rc.Cluster }
func (rc *RunContext) GetNamespace() string {
if rc.Opts.Namespace != "" {
return rc.Opts.Namespace
}
var defaultNamespace string
for _, p := range rc.GetPipelines() {
if p.Deploy.KubectlDeploy != nil && p.Deploy.KubectlDeploy.DefaultNamespace != nil {
if defaultNamespace != "" {
log.Entry(context.TODO()).Warn("multiple deploy.kubectl.defaultNamespace values set, only last pipeline's value will be used")
}
defaultNamespace = *p.Deploy.KubectlDeploy.DefaultNamespace
}
}
if defaultNamespace != "" {
defaultNamespace, err := util.ExpandEnvTemplate(defaultNamespace, nil)
if err != nil {
return ""
}
return defaultNamespace
}
b, err := util.RunCmdOutOnce(context.Background(), exec.Command("kubectl", "config", "view", "--minify", "-o", "jsonpath='{..namespace}'"))
if err != nil {
return rc.Opts.Namespace
}
return strings.Trim(string(b), "'")
}
func (rc *RunContext) AutoBuild() bool { return rc.Opts.AutoBuild }
func (rc *RunContext) DisableMultiPlatformBuild() bool { return rc.Opts.DisableMultiPlatformBuild }
func (rc *RunContext) CheckClusterNodePlatforms() bool {
return rc.Opts.CheckClusterNodePlatforms && !rc.IsMultiCluster()
}
func (rc *RunContext) AutoDeploy() bool { return rc.Opts.AutoDeploy }
func (rc *RunContext) AutoSync() bool { return rc.Opts.AutoSync }
func (rc *RunContext) ContainerDebugging() bool { return rc.Opts.ContainerDebugging }
func (rc *RunContext) CacheArtifacts() bool { return rc.Opts.CacheArtifacts }
func (rc *RunContext) CacheFile() string { return rc.Opts.CacheFile }
func (rc *RunContext) ConfigurationFile() string { return rc.Opts.ConfigurationFile }
func (rc *RunContext) CustomLabels() []string { return rc.Opts.CustomLabels }
func (rc *RunContext) CustomTag() string { return rc.Opts.CustomTag }
func (rc *RunContext) DefaultRepo() *string { return rc.Cluster.DefaultRepo.Value() }
func (rc *RunContext) MultiLevelRepo() *bool { return rc.Opts.MultiLevelRepo }
func (rc *RunContext) IsMultiCluster() bool { return rc.Pipelines.IsMultiCluster() }
func (rc *RunContext) Mode() config.RunMode { return rc.Opts.Mode() }
func (rc *RunContext) DryRun() bool { return rc.Opts.DryRun }
func (rc *RunContext) ForceDeploy() bool { return rc.Opts.Force }
func (rc *RunContext) GetKubeConfig() string { return rc.Opts.KubeConfig }
func (rc *RunContext) GetKubeNamespace() string { return rc.Opts.Namespace }
func (rc *RunContext) GlobalConfig() string { return rc.Opts.GlobalConfig }
func (rc *RunContext) HydratedManifests() []string { return rc.Opts.HydratedManifests }
func (rc *RunContext) LoadImages() bool { return rc.Cluster.LoadImages }
func (rc *RunContext) ForceLoadImages() bool { return rc.Opts.ForceLoadImages }
func (rc *RunContext) MinikubeProfile() string { return rc.Opts.MinikubeProfile }
func (rc *RunContext) Muted() config.Muted { return rc.Opts.Muted }
func (rc *RunContext) NoPruneChildren() bool { return rc.Opts.NoPruneChildren }
func (rc *RunContext) Notification() bool { return rc.Opts.Notification }
func (rc *RunContext) PortForward() bool { return rc.Opts.PortForward.Enabled() }
func (rc *RunContext) PortForwardOptions() config.PortForwardOptions { return rc.Opts.PortForward }
func (rc *RunContext) Prune() bool { return rc.Opts.Prune() }
func (rc *RunContext) RenderOnly() bool { return rc.Opts.RenderOnly }
func (rc *RunContext) RenderOutput() string { return rc.Opts.RenderOutput }
func (rc *RunContext) StatusCheck() *bool { return rc.Opts.StatusCheck.Value() }
func (rc *RunContext) IterativeStatusCheck() bool { return rc.Opts.IterativeStatusCheck }
func (rc *RunContext) FastFailStatusCheck() bool { return rc.Opts.FastFailStatusCheck }
func (rc *RunContext) Tail() bool { return rc.Opts.Tail }
func (rc *RunContext) Trigger() string { return rc.Opts.Trigger }
func (rc *RunContext) WaitForDeletions() config.WaitForDeletions { return rc.Opts.WaitForDeletions }
func (rc *RunContext) WatchPollInterval() int { return rc.Opts.WatchPollInterval }
func (rc *RunContext) BuildConcurrency() int { return rc.Opts.BuildConcurrency }
func (rc *RunContext) IsMultiConfig() bool { return rc.Pipelines.IsMultiPipeline() }
func (rc *RunContext) IsDefaultKubeContext() bool { return rc.Opts.KubeContext == "" }
func (rc *RunContext) GetRunID() string { return rc.RunID }
func (rc *RunContext) RPCPort() *int { return rc.Opts.RPCPort.Value() }
func (rc *RunContext) RPCHTTPPort() *int { return rc.Opts.RPCHTTPPort.Value() }
func (rc *RunContext) PushImages() config.BoolOrUndefined { return rc.Opts.PushImages }
func (rc *RunContext) TransformRulesFile() string { return rc.Opts.TransformRulesFile }
func (rc *RunContext) VerifyDockerNetwork() string { return rc.Opts.VerifyDockerNetwork }
func (rc *RunContext) JSONParseConfig() latest.JSONParseConfig {
return rc.DefaultPipeline().Deploy.Logs.JSONParse
}
func (rc *RunContext) EnablePlatformNodeAffinityInRenderedManifests() bool {
return rc.Opts.EnablePlatformNodeAffinity && rc.Cluster.IsMixedPlatform
}
func (rc *RunContext) EnableGKEARMNodeTolerationInRenderedManifests() bool {
return rc.Opts.EnableGKEARMNodeToleration
}
func (rc *RunContext) DigestSource() string {
if rc.Opts.DigestSource != "" {
return rc.Opts.DigestSource
}
if rc.Cluster.Local {
return constants.TagDigestSource
}
return constants.RemoteDigestSource
}
func getConfigName(configName string) string {
pipelineConfigName := configName
if len(pipelineConfigName) == 0 {
configNameUUID, _ := uuid.NewUUID()
pipelineConfigName = configNameUUID.String()
}
return pipelineConfigName
}
func GetRunContext(ctx context.Context, opts config.SkaffoldOptions, configs []schemaUtil.VersionedConfig) (*RunContext, error) {
pipelines := make(map[string]latest.Pipeline)
var orderedConfigs []string
for _, cfg := range configs {
if cfg != nil {
pipeline := cfg.(*latest.SkaffoldConfig).Pipeline
cfgName := getConfigName(cfg.(*latest.SkaffoldConfig).Metadata.Name)
pipelines[cfgName] = pipeline
orderedConfigs = append(orderedConfigs, cfgName)
}
}
kubeConfig, err := kubectx.CurrentConfig()
if err != nil {
return nil, fmt.Errorf("getting current cluster context: %w", err)
}
kubeContext := kubeConfig.CurrentContext
log.Entry(context.TODO()).Infof("Using kubectl context: %s", kubeContext)
// TODO(dgageot): this should be the folder containing skaffold.yaml. Should also be moved elsewhere.
cwd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("finding current directory: %w", err)
}
// combine all provided lists of insecure registries into a map
cfgRegistries, err := config.GetInsecureRegistries(opts.GlobalConfig)
if err != nil {
log.Entry(context.TODO()).Warn("error retrieving insecure registries from global config: push/pull issues may exist...")
}
var regList []string
regList = append(regList, opts.InsecureRegistries...)
for _, cfgName := range orderedConfigs {
cfg := pipelines[cfgName]
regList = append(regList, cfg.Build.InsecureRegistries...)
}
regList = append(regList, cfgRegistries...)
insecureRegistries := make(map[string]bool, len(regList))
for _, r := range regList {
insecureRegistries[r] = true
}
ps := NewPipelines(pipelines, orderedConfigs)
// TODO(https://github.com/GoogleContainerTools/skaffold/issues/3668):
// remove minikubeProfile from here and instead detect it by matching the
// kubecontext API Server to minikube profiles
cluster, err := config.GetCluster(ctx, config.GetClusterOpts{
ConfigFile: opts.GlobalConfig,
DefaultRepo: opts.DefaultRepo,
MinikubeProfile: opts.MinikubeProfile,
DetectMinikube: opts.DetectMinikube,
})
if err != nil {
return nil, fmt.Errorf("getting cluster: %w", err)
}
runID := uuid.New().String()
return &RunContext{
Opts: opts,
Pipelines: ps,
WorkingDir: cwd,
KubeContext: kubeContext,
InsecureRegistries: insecureRegistries,
Cluster: cluster,
RunID: runID,
}, nil
}