forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory_client_access.go
515 lines (430 loc) · 16.9 KB
/
factory_client_access.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
package clientcmd
import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/golang/glog"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/discovery"
restclient "k8s.io/client-go/rest"
kclientcmd "k8s.io/client-go/tools/clientcmd"
kclientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/util/homedir"
fedclientset "k8s.io/kubernetes/federation/client/clientset_generated/federation_internalclientset"
kapi "k8s.io/kubernetes/pkg/api"
kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
"k8s.io/kubernetes/pkg/kubectl"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
kprinters "k8s.io/kubernetes/pkg/printers"
"github.com/openshift/origin/pkg/client"
"github.com/openshift/origin/pkg/cmd/cli/config"
"github.com/openshift/origin/pkg/cmd/cli/describe"
deployapi "github.com/openshift/origin/pkg/deploy/apis/apps"
deploycmd "github.com/openshift/origin/pkg/deploy/cmd"
imageutil "github.com/openshift/origin/pkg/image/util"
routegen "github.com/openshift/origin/pkg/route/generator"
)
type ring0Factory struct {
clientConfig kclientcmd.ClientConfig
imageResolutionOptions FlagBinder
kubeClientAccessFactory kcmdutil.ClientAccessFactory
}
type ClientAccessFactory interface {
kcmdutil.ClientAccessFactory
Clients() (*client.Client, kclientset.Interface, error)
OpenShiftClientConfig() kclientcmd.ClientConfig
ImageResolutionOptions() FlagBinder
}
func NewClientAccessFactory(optionalClientConfig kclientcmd.ClientConfig) ClientAccessFactory {
flags := pflag.NewFlagSet("", pflag.ContinueOnError)
clientConfig := optionalClientConfig
if optionalClientConfig == nil {
// TODO: there should be two client configs, one for OpenShift, and one for Kubernetes
clientConfig = DefaultClientConfig(flags)
clientConfig = defaultingClientConfig{clientConfig}
}
return &ring0Factory{
clientConfig: clientConfig,
imageResolutionOptions: &imageResolutionOptions{},
kubeClientAccessFactory: kcmdutil.NewClientAccessFactoryFromDiscovery(flags, clientConfig, &discoveryFactory{clientConfig: clientConfig}),
}
}
type discoveryFactory struct {
clientConfig kclientcmd.ClientConfig
}
func (f *discoveryFactory) DiscoveryClient() (discovery.CachedDiscoveryInterface, error) {
// Output using whatever version was negotiated in the client cache. The
// version we decode with may not be the same as what the server requires.
cfg, err := f.clientConfig.ClientConfig()
if err != nil {
return nil, err
}
// given 25 groups with one-ish version each, discovery needs to make 50 requests
// double it just so we don't end up here again for a while. This config is only used for discovery.
cfg.Burst = 100
// at this point we've negotiated and can get the client
oclient, err := client.New(cfg)
if err != nil {
return nil, err
}
// TODO: k8s dir is different, I guess we should align
// cacheDir := computeDiscoverCacheDir(filepath.Join(homedir.HomeDir(), ".kube", "cache", "discovery"), cfg.Host)
cacheDir := computeDiscoverCacheDir(filepath.Join(homedir.HomeDir(), ".kube"), cfg.Host)
return kcmdutil.NewCachedDiscoveryClient(client.NewDiscoveryClient(oclient.RESTClient), cacheDir, time.Duration(10*time.Minute)), nil
}
func DefaultClientConfig(flags *pflag.FlagSet) kclientcmd.ClientConfig {
loadingRules := config.NewOpenShiftClientConfigLoadingRules()
flags.StringVar(&loadingRules.ExplicitPath, config.OpenShiftConfigFlagName, "", "Path to the config file to use for CLI requests.")
cobra.MarkFlagFilename(flags, config.OpenShiftConfigFlagName)
// set our explicit defaults
defaultOverrides := &kclientcmd.ConfigOverrides{ClusterDefaults: kclientcmdapi.Cluster{Server: os.Getenv("KUBERNETES_MASTER")}}
loadingRules.DefaultClientConfig = kclientcmd.NewDefaultClientConfig(kclientcmdapi.Config{}, defaultOverrides)
overrides := &kclientcmd.ConfigOverrides{ClusterDefaults: defaultOverrides.ClusterDefaults}
overrideFlags := kclientcmd.RecommendedConfigOverrideFlags("")
overrideFlags.ContextOverrideFlags.Namespace.ShortName = "n"
overrideFlags.AuthOverrideFlags.Username.LongName = ""
overrideFlags.AuthOverrideFlags.Password.LongName = ""
kclientcmd.BindOverrideFlags(overrides, flags, overrideFlags)
cobra.MarkFlagFilename(flags, overrideFlags.AuthOverrideFlags.ClientCertificate.LongName)
cobra.MarkFlagFilename(flags, overrideFlags.AuthOverrideFlags.ClientKey.LongName)
cobra.MarkFlagFilename(flags, overrideFlags.ClusterOverrideFlags.CertificateAuthority.LongName)
clientConfig := kclientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, overrides)
return clientConfig
}
func (f *ring0Factory) Clients() (*client.Client, kclientset.Interface, error) {
kubeClientSet, err := f.ClientSet()
if err != nil {
return nil, nil, err
}
cfg, err := f.clientConfig.ClientConfig()
if err != nil {
return nil, nil, err
}
openShiftClient, err := client.New(cfg)
if err != nil {
return nil, nil, err
}
return openShiftClient, kubeClientSet, nil
}
func (f *ring0Factory) OpenShiftClientConfig() kclientcmd.ClientConfig {
return f.clientConfig
}
func (f *ring0Factory) DiscoveryClient() (discovery.CachedDiscoveryInterface, error) {
return f.kubeClientAccessFactory.DiscoveryClient()
}
func (f *ring0Factory) ClientSet() (kclientset.Interface, error) {
return f.kubeClientAccessFactory.ClientSet()
}
func (f *ring0Factory) ClientSetForVersion(requiredVersion *schema.GroupVersion) (kclientset.Interface, error) {
return f.kubeClientAccessFactory.ClientSetForVersion(requiredVersion)
}
func (f *ring0Factory) ClientConfig() (*restclient.Config, error) {
return f.kubeClientAccessFactory.ClientConfig()
}
func (f *ring0Factory) BareClientConfig() (*restclient.Config, error) {
return f.clientConfig.ClientConfig()
}
func (f *ring0Factory) ClientConfigForVersion(requiredVersion *schema.GroupVersion) (*restclient.Config, error) {
return f.kubeClientAccessFactory.ClientConfigForVersion(nil)
}
func (f *ring0Factory) RESTClient() (*restclient.RESTClient, error) {
return f.kubeClientAccessFactory.RESTClient()
}
func (f *ring0Factory) FederationClientSetForVersion(version *schema.GroupVersion) (fedclientset.Interface, error) {
return f.kubeClientAccessFactory.FederationClientSetForVersion(version)
}
func (f *ring0Factory) FederationClientForVersion(version *schema.GroupVersion) (*restclient.RESTClient, error) {
return f.kubeClientAccessFactory.FederationClientForVersion(version)
}
func (f *ring0Factory) Decoder(toInternal bool) runtime.Decoder {
return f.kubeClientAccessFactory.Decoder(toInternal)
}
func (f *ring0Factory) JSONEncoder() runtime.Encoder {
return f.kubeClientAccessFactory.JSONEncoder()
}
func (f *ring0Factory) UpdatePodSpecForObject(obj runtime.Object, fn func(*kapi.PodSpec) error) (bool, error) {
switch t := obj.(type) {
case *deployapi.DeploymentConfig:
template := t.Spec.Template
if template == nil {
t.Spec.Template = template
template = &kapi.PodTemplateSpec{}
}
return true, fn(&template.Spec)
default:
return f.kubeClientAccessFactory.UpdatePodSpecForObject(obj, fn)
}
}
func (f *ring0Factory) MapBasedSelectorForObject(object runtime.Object) (string, error) {
switch t := object.(type) {
case *deployapi.DeploymentConfig:
return kubectl.MakeLabels(t.Spec.Selector), nil
default:
return f.kubeClientAccessFactory.MapBasedSelectorForObject(object)
}
}
func (f *ring0Factory) PortsForObject(object runtime.Object) ([]string, error) {
switch t := object.(type) {
case *deployapi.DeploymentConfig:
return getPorts(t.Spec.Template.Spec), nil
default:
return f.kubeClientAccessFactory.PortsForObject(object)
}
}
func (f *ring0Factory) ProtocolsForObject(object runtime.Object) (map[string]string, error) {
switch t := object.(type) {
case *deployapi.DeploymentConfig:
return getProtocols(t.Spec.Template.Spec), nil
default:
return f.kubeClientAccessFactory.ProtocolsForObject(object)
}
}
func (f *ring0Factory) LabelsForObject(object runtime.Object) (map[string]string, error) {
return f.kubeClientAccessFactory.LabelsForObject(object)
}
func (f *ring0Factory) FlagSet() *pflag.FlagSet {
return f.kubeClientAccessFactory.FlagSet()
}
func (f *ring0Factory) Command(cmd *cobra.Command, showSecrets bool) string {
return f.kubeClientAccessFactory.Command(cmd, showSecrets)
}
func (f *ring0Factory) BindFlags(flags *pflag.FlagSet) {
f.kubeClientAccessFactory.BindFlags(flags)
}
func (f *ring0Factory) BindExternalFlags(flags *pflag.FlagSet) {
f.kubeClientAccessFactory.BindExternalFlags(flags)
}
func (f *ring0Factory) DefaultResourceFilterOptions(cmd *cobra.Command, withNamespace bool) *kprinters.PrintOptions {
return f.kubeClientAccessFactory.DefaultResourceFilterOptions(cmd, withNamespace)
}
func (f *ring0Factory) DefaultResourceFilterFunc() kubectl.Filters {
return f.kubeClientAccessFactory.DefaultResourceFilterFunc()
}
func (f *ring0Factory) SuggestedPodTemplateResources() []schema.GroupResource {
return f.kubeClientAccessFactory.SuggestedPodTemplateResources()
}
// Saves current resource name (or alias if any) in PrintOptions. Once saved, it will not be overwritten by the
// kubernetes resource alias look-up, as it will notice a non-empty value in `options.Kind`
func (f *ring0Factory) Printer(mapping *meta.RESTMapping, options kprinters.PrintOptions) (kprinters.ResourcePrinter, error) {
if mapping != nil {
options.Kind = mapping.Resource
if alias, ok := resourceShortFormFor(mapping.Resource); ok {
options.Kind = alias
}
}
return describe.NewHumanReadablePrinter(f.JSONEncoder(), f.Decoder(true), options), nil
}
func (f *ring0Factory) Pauser(info *resource.Info) ([]byte, error) {
switch t := info.Object.(type) {
case *deployapi.DeploymentConfig:
if t.Spec.Paused {
return nil, errors.New("is already paused")
}
t.Spec.Paused = true
// TODO: Pause the deployer containers.
return runtime.Encode(f.JSONEncoder(), info.Object)
default:
return f.kubeClientAccessFactory.Pauser(info)
}
}
// ImageResolutionOptions provides the "--source" flag to commands that deal with images
// and need to provide extra capabilities for working with ImageStreamTags and
// ImageStreamImages.
type imageResolutionOptions struct {
bound bool
Source string
}
func (o *imageResolutionOptions) Bound() bool {
return o.bound
}
func (o *imageResolutionOptions) Bind(f *pflag.FlagSet) {
if o.Bound() {
return
}
f.StringVarP(&o.Source, "source", "", "istag", "The image source type; valid types are 'imagestreamtag', 'istag', 'imagestreamimage', 'isimage', and 'docker'")
o.bound = true
}
func (f *ring0Factory) ImageResolutionOptions() FlagBinder {
return f.imageResolutionOptions
}
func (f *ring0Factory) ResolveImage(image string) (string, error) {
options := f.imageResolutionOptions.(*imageResolutionOptions)
if imageutil.IsDocker(options.Source) {
return f.kubeClientAccessFactory.ResolveImage(image)
}
oc, _, err := f.Clients()
if err != nil {
return "", err
}
namespace, _, err := f.DefaultNamespace()
if err != nil {
return "", err
}
return imageutil.ResolveImagePullSpec(oc, oc, options.Source, image, namespace)
}
func (f *ring0Factory) Resumer(info *resource.Info) ([]byte, error) {
switch t := info.Object.(type) {
case *deployapi.DeploymentConfig:
if !t.Spec.Paused {
return nil, errors.New("is not paused")
}
t.Spec.Paused = false
// TODO: Resume the deployer containers.
return runtime.Encode(f.JSONEncoder(), info.Object)
default:
return f.kubeClientAccessFactory.Resumer(info)
}
}
func (f *ring0Factory) DefaultNamespace() (string, bool, error) {
return f.kubeClientAccessFactory.DefaultNamespace()
}
func DefaultGenerators(cmdName string) map[string]kubectl.Generator {
generators := map[string]map[string]kubectl.Generator{}
generators["run"] = map[string]kubectl.Generator{
"deploymentconfig/v1": deploycmd.BasicDeploymentConfigController{},
"run-controller/v1": kubectl.BasicReplicationController{}, // legacy alias for run/v1
}
generators["expose"] = map[string]kubectl.Generator{
"route/v1": routegen.RouteGenerator{},
}
return generators[cmdName]
}
func (f *ring0Factory) Generators(cmdName string) map[string]kubectl.Generator {
originGenerators := DefaultGenerators(cmdName)
kubeGenerators := f.kubeClientAccessFactory.Generators(cmdName)
ret := map[string]kubectl.Generator{}
for k, v := range kubeGenerators {
ret[k] = v
}
for k, v := range originGenerators {
ret[k] = v
}
return ret
}
func (f *ring0Factory) CanBeExposed(kind schema.GroupKind) error {
if deployapi.IsKindOrLegacy("DeploymentConfig", kind) {
return nil
}
return f.kubeClientAccessFactory.CanBeExposed(kind)
}
func (f *ring0Factory) CanBeAutoscaled(kind schema.GroupKind) error {
if deployapi.IsKindOrLegacy("DeploymentConfig", kind) {
return nil
}
return f.kubeClientAccessFactory.CanBeAutoscaled(kind)
}
func (f *ring0Factory) EditorEnvs() []string {
return []string{"OC_EDITOR", "EDITOR"}
}
func (f *ring0Factory) PrintObjectSpecificMessage(obj runtime.Object, out io.Writer) {}
// defaultingClientConfig detects whether the provided config is the default, and if
// so returns an error that indicates the user should set up their config.
type defaultingClientConfig struct {
nested kclientcmd.ClientConfig
}
// RawConfig calls the nested method
func (c defaultingClientConfig) RawConfig() (kclientcmdapi.Config, error) {
return c.nested.RawConfig()
}
// Namespace calls the nested method, and if an empty config error is returned
// it checks for the same default as kubectl - the value of POD_NAMESPACE or
// "default".
func (c defaultingClientConfig) Namespace() (string, bool, error) {
namespace, ok, err := c.nested.Namespace()
if err == nil {
return namespace, ok, nil
}
if !kclientcmd.IsEmptyConfig(err) {
return "", false, err
}
// This way assumes you've set the POD_NAMESPACE environment variable using the downward API.
// This check has to be done first for backwards compatibility with the way InClusterConfig was originally set up
if ns := os.Getenv("POD_NAMESPACE"); ns != "" {
return ns, true, nil
}
// Fall back to the namespace associated with the service account token, if available
if data, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil {
if ns := strings.TrimSpace(string(data)); len(ns) > 0 {
return ns, true, nil
}
}
return metav1.NamespaceDefault, false, nil
}
// ConfigAccess implements ClientConfig
func (c defaultingClientConfig) ConfigAccess() kclientcmd.ConfigAccess {
return c.nested.ConfigAccess()
}
type errConfigurationMissing struct {
err error
}
func (e errConfigurationMissing) Error() string {
return fmt.Sprintf("%v", e.err)
}
func IsConfigurationMissing(err error) bool {
switch err.(type) {
case errConfigurationMissing:
return true
}
return kclientcmd.IsContextNotFound(err)
}
// ClientConfig returns a complete client config
func (c defaultingClientConfig) ClientConfig() (*restclient.Config, error) {
cfg, err := c.nested.ClientConfig()
if err == nil {
return cfg, nil
}
if !kclientcmd.IsEmptyConfig(err) {
return nil, err
}
// TODO: need to expose inClusterConfig upstream and use that
if icc, err := restclient.InClusterConfig(); err == nil {
glog.V(4).Infof("Using in-cluster configuration")
return icc, nil
}
return nil, errConfigurationMissing{fmt.Errorf(`Missing or incomplete configuration info. Please login or point to an existing, complete config file:
1. Via the command-line flag --config
2. Via the KUBECONFIG environment variable
3. In your home directory as ~/.kube/config
To view or setup config directly use the 'config' command.`)}
}
// computeDiscoverCacheDir takes the parentDir and the host and comes up with a "usually non-colliding" name.
func computeDiscoverCacheDir(parentDir, host string) string {
// strip the optional scheme from host if its there:
schemelessHost := strings.Replace(strings.Replace(host, "https://", "", 1), "http://", "", 1)
// now do a simple collapse of non-AZ09 characters. Collisions are possible but unlikely. Even if we do collide the problem is short lived
safeHost := overlyCautiousIllegalFileCharacters.ReplaceAllString(schemelessHost, "_")
return filepath.Join(parentDir, safeHost)
}
// overlyCautiousIllegalFileCharacters matches characters that *might* not be supported. Windows is really restrictive, so this is really restrictive
var overlyCautiousIllegalFileCharacters = regexp.MustCompile(`[^(\w/\.)]`)
func getPorts(spec kapi.PodSpec) []string {
result := []string{}
for _, container := range spec.Containers {
for _, port := range container.Ports {
result = append(result, strconv.Itoa(int(port.ContainerPort)))
}
}
return result
}
func getProtocols(spec kapi.PodSpec) map[string]string {
result := make(map[string]string)
for _, container := range spec.Containers {
for _, port := range container.Ports {
result[strconv.Itoa(int(port.ContainerPort))] = string(port.Protocol)
}
}
return result
}