Merge pull request #46299 from ncdc/fix-DirectClientConfig-Namespace-override

Automatic merge from submit-queue (batch tested with PRs 46299, 46309, 46311, 46303, 46150)

Fix in-cluster kubectl --namespace override

**What this PR does / why we need it**:
Before this change, if the config was empty, ConfirmUsable() would
return an "invalid configuration" error instead of examining and
honoring the value of the --namespace flag. This change looks at the
overrides first, and returns the overridden value if it exists before
attempting to check if the config is usable. This is most applicable to
in-cluster clients, where they don't have a kubeconfig but they do have
a token and can use KUBERNETES_SERVICE_HOST/_PORT.

**Which issue this PR fixes** *(optional, in `fixes #<issue number>(, fixes #<issue_number>, ...)` format, will close that issue when PR gets merged)*: fixes #

**Special notes for your reviewer**:

**Release note**:

```release-note
The --namespace flag is now honored for in-cluster clients that have an empty configuration.
```

@kubernetes/sig-api-machinery-pr-reviews @fabianofranz @liggitt @deads2k @smarterclayton @caesarxuchao @soltysh
This commit is contained in:
Kubernetes Submit Queue 2017-05-24 23:18:59 -07:00 committed by GitHub
commit 3c2e6a9f4d
2 changed files with 31 additions and 5 deletions

View File

@ -296,6 +296,14 @@ func canIdentifyUser(config restclient.Config) bool {
// Namespace implements ClientConfig
func (config *DirectClientConfig) Namespace() (string, bool, error) {
if config.overrides != nil && config.overrides.Context.Namespace != "" {
// In the event we have an empty config but we do have a namespace override, we should return
// the namespace override instead of having config.ConfirmUsable() return an error. This allows
// things like in-cluster clients to execute `kubectl get pods --namespace=foo` and have the
// --namespace flag honored instead of being ignored.
return config.overrides.Context.Namespace, true, nil
}
if err := config.ConfirmUsable(); err != nil {
return "", false, err
}
@ -309,11 +317,7 @@ func (config *DirectClientConfig) Namespace() (string, bool, error) {
return v1.NamespaceDefault, false, nil
}
overridden := false
if config.overrides != nil && config.overrides.Context.Namespace != "" {
overridden = true
}
return configContext.Namespace, overridden, nil
return configContext.Namespace, false, nil
}
// ConfigAccess implements ClientConfig

View File

@ -504,3 +504,25 @@ func matchByteArg(expected, got []byte, t *testing.T) {
t.Errorf("Expected %v, got %v", expected, got)
}
}
func TestNamespaceOverride(t *testing.T) {
config := &DirectClientConfig{
overrides: &ConfigOverrides{
Context: clientcmdapi.Context{
Namespace: "foo",
},
},
}
ns, overridden, err := config.Namespace()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if !overridden {
t.Errorf("Expected overridden = true")
}
matchStringArg("foo", ns, t)
}