sigs.k8s.io/cluster-api-provider-aws@v1.5.5/util/system/util.go (about) 1 /* 2 Copyright 2021 The Kubernetes 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 system 18 19 import ( 20 "fmt" 21 "os" 22 "path/filepath" 23 24 "github.com/pkg/errors" 25 ) 26 27 const ( 28 // namespaceEnvVarName is the env var coming from DownwardAPI in the manager manifest. 29 namespaceEnvVarName = "POD_NAMESPACE" 30 // defaultNamespace is the default value from manifest. 31 defaultNamespace = "capa-system" 32 // inClusterNamespacePath is the file the default namespace to be used for namespaced API operations is placed at. 33 inClusterNamespacePath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace" 34 ) 35 36 // GetManagerNamespace return the namespace where the controller is running. 37 func GetManagerNamespace() string { 38 ns, err := GetNamespaceFromFile(inClusterNamespacePath) 39 if err == nil { 40 return ns 41 } 42 43 // If file is not there, check if env var is set, otherwise return the default namespace. 44 managerNamespace := os.Getenv(namespaceEnvVarName) 45 if managerNamespace == "" { 46 managerNamespace = defaultNamespace 47 } 48 return managerNamespace 49 } 50 51 // GetNamespaceFromFile returns the namespace from a file. 52 // This code is copied from controller-runtime, because it is a private method there. 53 // https://github.com/kubernetes-sigs/controller-runtime/blob/316aea4229158103123166a5e45076f1a86bd807/pkg/leaderelection/leader_election.go#L104 54 func GetNamespaceFromFile(nsFilePath string) (string, error) { 55 // Check whether the namespace file exists. 56 // If not, we are not running in cluster so can't guess the namespace. 57 58 if _, err := os.Stat(nsFilePath); os.IsNotExist(err) { 59 return "", errors.Wrapf(err, "not running in-cluster, please specify LeaderElectionNamespace") 60 } else if err != nil { 61 return "", errors.Wrapf(err, "error checking namespace file: %s", nsFilePath) 62 } 63 64 // Load the namespace file and return its content 65 namespace, err := os.ReadFile(filepath.Clean(nsFilePath)) 66 if err != nil { 67 return "", fmt.Errorf("error reading namespace file: %w", err) 68 } 69 return string(namespace), nil 70 }