1 /* 2 Copyright 2018 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 options 18 19 import ( 20 "flag" 21 "fmt" 22 "os" 23 "strings" 24 25 "github.com/spf13/pflag" 26 27 // libs that provide registration functions 28 "k8s.io/component-base/logs" 29 "k8s.io/component-base/version/verflag" 30 31 // ensure libs have a chance to globally register their flags 32 _ "k8s.io/kubernetes/pkg/credentialprovider/gcp" 33 ) 34 35 // AddGlobalFlags explicitly registers flags that libraries (glog, verflag, etc.) register 36 // against the global flagsets from "flag" and "github.com/spf13/pflag". 37 // We do this in order to prevent unwanted flags from leaking into the Kubelet's flagset. 38 func AddGlobalFlags(fs *pflag.FlagSet) { 39 addCadvisorFlags(fs) 40 addCredentialProviderFlags(fs) 41 verflag.AddFlags(fs) 42 logs.AddFlags(fs, logs.SkipLoggingConfigurationFlags()) 43 } 44 45 // normalize replaces underscores with hyphens 46 // we should always use hyphens instead of underscores when registering kubelet flags 47 func normalize(s string) string { 48 return strings.Replace(s, "_", "-", -1) 49 } 50 51 // register adds a flag to local that targets the Value associated with the Flag named globalName in global 52 func register(global *flag.FlagSet, local *pflag.FlagSet, globalName string) { 53 if f := global.Lookup(globalName); f != nil { 54 pflagFlag := pflag.PFlagFromGoFlag(f) 55 pflagFlag.Name = normalize(pflagFlag.Name) 56 local.AddFlag(pflagFlag) 57 } else { 58 panic(fmt.Sprintf("failed to find flag in global flagset (flag): %s", globalName)) 59 } 60 } 61 62 // registerDeprecated registers the flag with register, and then marks it deprecated 63 func registerDeprecated(global *flag.FlagSet, local *pflag.FlagSet, globalName, deprecated string) { 64 register(global, local, globalName) 65 local.Lookup(normalize(globalName)).Deprecated = deprecated 66 } 67 68 // addCredentialProviderFlags adds flags from k8s.io/kubernetes/pkg/credentialprovider 69 func addCredentialProviderFlags(fs *pflag.FlagSet) { 70 // lookup flags in global flag set and re-register the values with our flagset 71 local := pflag.NewFlagSet(os.Args[0], pflag.ExitOnError) 72 73 fs.AddFlagSet(local) 74 } 75