github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/deploy/util/namespaces.go (about) 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 17 package util 18 19 import ( 20 "fmt" 21 "sort" 22 23 kubectx "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" 24 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest" 25 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" 26 ) 27 28 // GetAllPodNamespaces lists the namespaces that should be watched. 29 // + The namespace passed on the command line 30 // + Current kube context's namespace 31 // + Namespaces referenced in Helm releases 32 func GetAllPodNamespaces(configNamespace string, pipelines []latest.Pipeline) ([]string, error) { 33 nsMap := make(map[string]bool) 34 35 if configNamespace == "" { 36 // Get current kube context's namespace 37 config, err := kubectx.CurrentConfig() 38 if err != nil { 39 return nil, fmt.Errorf("getting k8s configuration: %w", err) 40 } 41 42 context, ok := config.Contexts[config.CurrentContext] 43 if ok { 44 nsMap[context.Namespace] = true 45 } else { 46 nsMap[""] = true 47 } 48 } else { 49 nsMap[configNamespace] = true 50 } 51 52 // Set additional namespaces each helm release referenced 53 helmReleasesNamespaces, err := collectHelmReleasesNamespaces(pipelines) 54 if err != nil { 55 return nil, fmt.Errorf("collecting helm releases namespaces: %w", err) 56 } 57 for _, namespace := range helmReleasesNamespaces { 58 nsMap[namespace] = true 59 } 60 61 // Collate the slice of namespaces. 62 namespaces := make([]string, 0, len(nsMap)) 63 for ns := range nsMap { 64 namespaces = append(namespaces, ns) 65 } 66 67 sort.Strings(namespaces) 68 return namespaces, nil 69 } 70 71 func collectHelmReleasesNamespaces(pipelines []latest.Pipeline) ([]string, error) { 72 var namespaces []string 73 for _, cfg := range pipelines { 74 if cfg.Deploy.HelmDeploy != nil { 75 for _, release := range cfg.Deploy.HelmDeploy.Releases { 76 if release.Namespace != "" { 77 templatedNamespace, err := util.ExpandEnvTemplateOrFail(release.Namespace, nil) 78 if err != nil { 79 return []string{}, fmt.Errorf("cannot parse the release namespace template: %w", err) 80 } 81 namespaces = append(namespaces, templatedNamespace) 82 } 83 } 84 } 85 } 86 return namespaces, nil 87 }