-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
util.go
574 lines (506 loc) · 16.8 KB
/
util.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/*
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 config
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/imdario/mergo"
"github.com/mitchellh/go-homedir"
api_errors "k8s.io/apimachinery/pkg/api/errors"
api_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/cluster"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/constants"
kubeclient "github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/kubernetes/client"
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/util"
timeutil "github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/util/time"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/yaml"
)
const (
defaultConfigDir = ".skaffold"
defaultConfigFile = "config"
)
var (
// config-file content
configFile *GlobalConfig
configFileErr error
configFileOnce sync.Once
// config for a kubeContext
config *ContextConfig
configErr error
configOnce sync.Once
ReadConfigFile = readConfigFileCached
GetConfigForCurrentKubectx = getConfigForCurrentKubectx
DiscoverLocalRegistry = discoverLocalRegistry
current = time.Now
// update global config with the time the survey was last taken
updateLastTaken = "skaffold config set --survey --global last-taken %s"
updateUserTaken = "skaffold config set --survey --global --id %s taken true"
// update global config with the time the survey was last prompted
updateLastPrompted = "skaffold config set --survey --global last-prompted %s"
)
// readConfigFileCached reads the specified file and returns the contents
// parsed into a GlobalConfig struct.
// This function will always return the identical data from the first read.
func readConfigFileCached(filename string) (*GlobalConfig, error) {
configFileOnce.Do(func() {
filenameOrDefault, err := ResolveConfigFile(filename)
if err != nil {
configFileErr = err
log.Entry(context.TODO()).Warnf("Could not load global Skaffold defaults. Error resolving config file %q", filenameOrDefault)
return
}
configFile, configFileErr = ReadConfigFileNoCache(filenameOrDefault)
if configFileErr == nil {
log.Entry(context.TODO()).Infof("Loaded Skaffold defaults from %q", filenameOrDefault)
}
})
return configFile, configFileErr
}
// ResolveConfigFile determines the default config location, if the configFile argument is empty.
func ResolveConfigFile(configFile string) (string, error) {
if configFile == "" {
home, err := homedir.Dir()
if err != nil {
return "", fmt.Errorf("retrieving home directory: %w", err)
}
configFile = filepath.Join(home, defaultConfigDir, defaultConfigFile)
}
return configFile, util.VerifyOrCreateFile(configFile)
}
// ReadConfigFileNoCache reads the given config yaml file and unmarshals the contents.
// Only visible for testing, use ReadConfigFile instead.
func ReadConfigFileNoCache(configFile string) (*GlobalConfig, error) {
contents, err := os.ReadFile(configFile)
if err != nil {
log.Entry(context.TODO()).Warnf("Could not load global Skaffold defaults. Error encounter while reading file %q", configFile)
return nil, fmt.Errorf("reading global config: %w", err)
}
config := GlobalConfig{}
if err := yaml.Unmarshal(contents, &config); err != nil {
log.Entry(context.TODO()).Warnf("Could not load global Skaffold defaults. Error encounter while unmarshalling the contents of file %q", configFile)
return nil, fmt.Errorf("unmarshalling global skaffold config: %w", err)
}
return &config, nil
}
// GetConfigForCurrentKubectx returns the specific config to be modified based on the kubeContext.
// Either returns the config corresponding to the provided or current context,
// or the global config.
func getConfigForCurrentKubectx(configFile string) (*ContextConfig, error) {
configOnce.Do(func() {
cfg, err := ReadConfigFile(configFile)
if err != nil {
configErr = err
return
}
kubeconfig, err := kubectx.CurrentConfig()
if err != nil {
configErr = err
return
}
config, configErr = getConfigForKubeContextWithGlobalDefaults(cfg, kubeconfig.CurrentContext)
})
return config, configErr
}
func getConfigForKubeContextWithGlobalDefaults(cfg *GlobalConfig, kubeContext string) (*ContextConfig, error) {
if kubeContext == "" {
if cfg.Global == nil {
return &ContextConfig{}, nil
}
return cfg.Global, nil
}
var mergedConfig ContextConfig
for _, contextCfg := range cfg.ContextConfigs {
if util.RegexEqual(contextCfg.Kubecontext, kubeContext) {
log.Entry(context.TODO()).Debugf("found config for context %q", kubeContext)
mergedConfig = *contextCfg
}
}
// in case there was no config for this kubeContext in cfg.ContextConfigs
mergedConfig.Kubecontext = kubeContext
if cfg.Global != nil {
// if values are unset for the current context, retrieve
// the global config and use its values as a fallback.
if err := mergo.Merge(&mergedConfig, cfg.Global, mergo.WithAppendSlice); err != nil {
return nil, fmt.Errorf("merging context-specific and global config: %w", err)
}
}
return &mergedConfig, nil
}
func GetDefaultRepo(configFile string, cliValue *string) (string, error) {
// CLI flag takes precedence.
if cliValue != nil {
return *cliValue, nil
}
cfg, err := GetConfigForCurrentKubectx(configFile)
if err != nil {
return "", err
}
if cfg.DefaultRepo != "" {
log.Entry(context.TODO()).Infof("Using default-repo=%s from config", cfg.DefaultRepo)
}
return cfg.DefaultRepo, nil
}
func GetMultiLevelRepo(configFile string) (*bool, error) {
cfg, err := GetConfigForCurrentKubectx(configFile)
if err != nil {
return nil, err
}
if cfg.MultiLevelRepo != nil {
log.Entry(context.TODO()).Infof("Using multi-level-repo=%t from config", *cfg.MultiLevelRepo)
}
return cfg.MultiLevelRepo, nil
}
func GetInsecureRegistries(configFile string) ([]string, error) {
cfg, err := GetConfigForCurrentKubectx(configFile)
if err != nil {
return nil, err
}
if len(cfg.InsecureRegistries) > 0 {
log.Entry(context.TODO()).Infof("Using insecure-registries=%v from config", cfg.InsecureRegistries)
}
return cfg.InsecureRegistries, nil
}
func GetDebugHelpersRegistry(configFile string) (string, error) {
cfg, err := GetConfigForCurrentKubectx(configFile)
if err != nil {
return "", err
}
if cfg.DebugHelpersRegistry != "" {
log.Entry(context.TODO()).Infof("Using debug-helpers-registry=%s from config", cfg.DebugHelpersRegistry)
return cfg.DebugHelpersRegistry, nil
}
return constants.DefaultDebugHelpersRegistry, nil
}
type GetClusterOpts struct {
ConfigFile string
DefaultRepo StringOrUndefined
MinikubeProfile string
DetectMinikube bool
}
func GetCluster(ctx context.Context, opts GetClusterOpts) (Cluster, error) {
cfg, err := GetConfigForCurrentKubectx(opts.ConfigFile)
if err != nil {
return Cluster{}, err
}
kubeContext := cfg.Kubecontext
isKindCluster, isK3dCluster := IsKindCluster(kubeContext), IsK3dCluster(kubeContext)
isMixedPlatform := IsMixedPlatformCluster(ctx, kubeContext)
var local bool
switch {
case opts.MinikubeProfile != "":
local = true
case cfg.LocalCluster != nil:
log.Entry(context.TODO()).Infof("Using local-cluster=%t from config", *cfg.LocalCluster)
local = *cfg.LocalCluster
case kubeContext == constants.DefaultMinikubeContext ||
kubeContext == constants.DefaultDockerForDesktopContext ||
kubeContext == constants.DefaultDockerDesktopContext ||
isKindCluster || isK3dCluster:
local = true
case opts.DetectMinikube:
local = cluster.GetClient().IsMinikube(ctx, kubeContext)
default:
local = false
}
var defaultRepo = opts.DefaultRepo
if local && defaultRepo.Value() == nil {
registry, err := DiscoverLocalRegistry(ctx, kubeContext)
switch {
case err != nil:
log.Entry(context.TODO()).Tracef("failed to discover local registry %v", err)
case registry != nil:
log.Entry(context.TODO()).Infof("using default-repo=%s from cluster configmap", *registry)
return Cluster{
Local: local,
LoadImages: false,
PushImages: true,
DefaultRepo: NewStringOrUndefined(registry),
IsMixedPlatform: isMixedPlatform,
}, nil
}
}
kindDisableLoad := cfg.KindDisableLoad != nil && *cfg.KindDisableLoad
k3dDisableLoad := cfg.K3dDisableLoad != nil && *cfg.K3dDisableLoad
// load images for local kind/k3d cluster unless explicitly disabled
loadImages := local && ((isKindCluster && !kindDisableLoad) || (isK3dCluster && !k3dDisableLoad))
// push images for remote cluster or local kind/k3d cluster with image loading disabled
pushImages := !local || (isKindCluster && kindDisableLoad) || (isK3dCluster && k3dDisableLoad)
return Cluster{
Local: local,
LoadImages: loadImages,
PushImages: pushImages,
DefaultRepo: defaultRepo,
IsMixedPlatform: isMixedPlatform,
}, nil
}
func IsMixedPlatformCluster(ctx context.Context, kubeContext string) bool {
client, err := kubeclient.Client(kubeContext)
if err != nil {
return false
}
nodes, err := client.CoreV1().Nodes().List(ctx, api_v1.ListOptions{})
if err != nil || nodes == nil {
return false
}
set := make(map[string]interface{})
for _, n := range nodes.Items {
set[fmt.Sprintf("%s/%s", n.Status.NodeInfo.OperatingSystem, n.Status.NodeInfo.Architecture)] = struct{}{}
}
return len(set) > 1
}
// IsKindCluster checks that the given `kubeContext` is talking to `kind`.
func IsKindCluster(kubeContext string) bool {
switch {
// With kind version < 0.6.0, the k8s context
// is `[CLUSTER NAME]@kind`.
// For eg: `cluster@kind`
// the default name is `kind@kind`
case strings.HasSuffix(kubeContext, "@kind"):
return true
// With kind version >= 0.6.0, the k8s context
// is `kind-[CLUSTER NAME]`.
// For eg: `kind-cluster`
// the default name is `kind-kind`
case strings.HasPrefix(kubeContext, "kind-"):
return true
default:
return false
}
}
// KindClusterName returns the internal kind name of a kubernetes cluster.
func KindClusterName(clusterName string) string {
switch {
// With kind version < 0.6.0, the k8s context
// is `[CLUSTER NAME]@kind`.
// For eg: `cluster@kind`
// the default name is `kind@kind`
case strings.HasSuffix(clusterName, "@kind"):
return strings.TrimSuffix(clusterName, "@kind")
// With kind version >= 0.6.0, the k8s context
// is `kind-[CLUSTER NAME]`.
// For eg: `kind-cluster`
// the default name is `kind-kind`
case strings.HasPrefix(clusterName, "kind-"):
return strings.TrimPrefix(clusterName, "kind-")
}
return clusterName
}
// IsK3dCluster checks that the given `kubeContext` is talking to `k3d`.
func IsK3dCluster(kubeContext string) bool {
return strings.HasPrefix(kubeContext, "k3d-")
}
// K3dClusterName returns the internal name of a k3d cluster.
func K3dClusterName(clusterName string) string {
if strings.HasPrefix(clusterName, "k3d-") {
return strings.TrimPrefix(clusterName, "k3d-")
}
return clusterName
}
func discoverLocalRegistry(ctx context.Context, kubeContext string) (*string, error) {
clientset, err := kubeclient.Client(kubeContext)
if err != nil {
return nil, err
}
configMap, err := clientset.CoreV1().ConfigMaps("kube-public").Get(ctx, "local-registry-hosting", api_v1.GetOptions{})
statusErr := &api_errors.StatusError{}
switch {
case errors.As(err, &statusErr) && statusErr.Status().Code == http.StatusNotFound:
return nil, nil
case err != nil:
return nil, err
}
data, ok := configMap.Data["localRegistryHosting.v1"]
if !ok {
return nil, errors.New("invalid local-registry-hosting ConfigMap")
}
dst := struct {
Host *string `yaml:"host"`
}{}
if err := yaml.Unmarshal([]byte(data), &dst); err != nil {
return nil, errors.New("invalid local-registry-hosting ConfigMap")
}
return dst.Host, nil
}
func IsUpdateCheckEnabled(configfile string) bool {
cfg, err := GetConfigForCurrentKubectx(configfile)
if err != nil {
return true
}
return IsUpdateCheckEnabledForContext(cfg)
}
func IsUpdateCheckEnabledForContext(cfg *ContextConfig) bool {
return cfg == nil || cfg.UpdateCheck == nil || *cfg.UpdateCheck
}
func ShouldDisplayUpdateMsg(configfile string) bool {
cfg, err := GetConfigForCurrentKubectx(configfile)
if err != nil {
return true
}
if cfg == nil || cfg.UpdateCheckConfig == nil {
return true
}
return !timeutil.LessThan(cfg.UpdateCheckConfig.LastPrompted, 24*time.Hour)
}
// UpdateMsgDisplayed updates the `last-prompted` config for `update-config` in
// the skaffold config
func UpdateMsgDisplayed(configFile string) error {
// Today's date
today := current().Format(time.RFC3339)
configFile, err := ResolveConfigFile(configFile)
if err != nil {
return err
}
fullConfig, err := ReadConfigFile(configFile)
if err != nil {
return err
}
if !IsUpdateCheckEnabledForContext(fullConfig.Global) {
return nil
}
if fullConfig.Global == nil {
fullConfig.Global = &ContextConfig{}
}
if fullConfig.Global.UpdateCheckConfig == nil {
fullConfig.Global.UpdateCheckConfig = &UpdateConfig{}
}
fullConfig.Global.UpdateCheckConfig.LastPrompted = today
err = WriteFullConfig(configFile, fullConfig)
return err
}
func UpdateHaTSSurveyTaken(configFile string) error {
// Today's date
today := current().Format(time.RFC3339)
ai := fmt.Sprintf(updateLastTaken, today)
aiErr := fmt.Errorf("could not automatically update the survey timestamp - please run `%s`", ai)
configFile, err := ResolveConfigFile(configFile)
if err != nil {
return aiErr
}
fullConfig, err := ReadConfigFile(configFile)
if err != nil {
return aiErr
}
if fullConfig.Global == nil {
fullConfig.Global = &ContextConfig{}
}
if fullConfig.Global.Survey == nil {
fullConfig.Global.Survey = &SurveyConfig{}
}
fullConfig.Global.Survey.LastTaken = today
err = WriteFullConfig(configFile, fullConfig)
if err != nil {
return aiErr
}
return err
}
func UpdateGlobalSurveyPrompted(configFile string) error {
// Today's date
today := current().Format(time.RFC3339)
ai := fmt.Sprintf(updateLastPrompted, today)
aiErr := fmt.Errorf("could not automatically update the survey prompted timestamp - please run `%s`", ai)
configFile, err := ResolveConfigFile(configFile)
if err != nil {
return aiErr
}
fullConfig, err := ReadConfigFile(configFile)
if err != nil {
return aiErr
}
if fullConfig.Global == nil {
fullConfig.Global = &ContextConfig{}
}
if fullConfig.Global.Survey == nil {
fullConfig.Global.Survey = &SurveyConfig{}
}
fullConfig.Global.Survey.LastPrompted = today
err = WriteFullConfig(configFile, fullConfig)
if err != nil {
return aiErr
}
return err
}
func UpdateGlobalCollectMetrics(configFile string, collectMetrics bool) error {
configFile, err := ResolveConfigFile(configFile)
if err != nil {
return err
}
fullConfig, err := ReadConfigFile(configFile)
if err != nil {
return err
}
if fullConfig.Global == nil {
fullConfig.Global = &ContextConfig{}
}
fullConfig.Global.CollectMetrics = &collectMetrics
err = WriteFullConfig(configFile, fullConfig)
if err != nil {
return err
}
return err
}
func WriteFullConfig(configFile string, cfg *GlobalConfig) error {
contents, err := yaml.Marshal(cfg)
if err != nil {
return fmt.Errorf("marshaling config: %w", err)
}
configFileOrDefault, err := ResolveConfigFile(configFile)
if err != nil {
return err
}
if err := os.WriteFile(configFileOrDefault, contents, 0644); err != nil {
return fmt.Errorf("writing config file: %w", err)
}
return nil
}
func UpdateUserSurveyTaken(configFile string, id string) error {
ai := fmt.Sprintf(updateUserTaken, id)
aiErr := fmt.Errorf("could not automatically update the survey prompted timestamp - please run `%s`", ai)
configFile, err := ResolveConfigFile(configFile)
if err != nil {
return aiErr
}
fullConfig, err := ReadConfigFile(configFile)
if err != nil {
return aiErr
}
if fullConfig.Global == nil {
fullConfig.Global = &ContextConfig{}
}
if fullConfig.Global.Survey == nil {
fullConfig.Global.Survey = &SurveyConfig{}
}
fullConfig.Global.Survey.UserSurveys = updatedUserSurveys(fullConfig.Global.Survey.UserSurveys, id)
err = WriteFullConfig(configFile, fullConfig)
if err != nil {
return aiErr
}
return nil
}
func updatedUserSurveys(us []*UserSurvey, id string) []*UserSurvey {
for _, s := range us {
if s.ID == id {
s.Taken = util.Ptr(true)
return us
}
}
return append(us, &UserSurvey{ID: id, Taken: util.Ptr(true)})
}