blob: d46dece4a78c4ee7b883b6a89b54ea056290cb0d [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package options
18
19import (
20 "fmt"
21 "time"
22
23 "github.com/spf13/pflag"
24 "k8s.io/apiserver/pkg/server"
25 clientgoinformers "k8s.io/client-go/informers"
26 clientgoclientset "k8s.io/client-go/kubernetes"
27 "k8s.io/client-go/rest"
28 "k8s.io/client-go/tools/clientcmd"
29)
30
31// CoreAPIOptions contains options to configure the connection to a core API Kubernetes apiserver.
32type CoreAPIOptions struct {
33 // CoreAPIKubeconfigPath is a filename for a kubeconfig file to contact the core API server with.
34 // If it is not set, the in cluster config is used.
35 CoreAPIKubeconfigPath string
36}
37
38func NewCoreAPIOptions() *CoreAPIOptions {
39 return &CoreAPIOptions{}
40}
41
42func (o *CoreAPIOptions) AddFlags(fs *pflag.FlagSet) {
43 if o == nil {
44 return
45 }
46
47 fs.StringVar(&o.CoreAPIKubeconfigPath, "kubeconfig", o.CoreAPIKubeconfigPath,
48 "kubeconfig file pointing at the 'core' kubernetes server.")
49}
50
51func (o *CoreAPIOptions) ApplyTo(config *server.RecommendedConfig) error {
52 if o == nil {
53 return nil
54 }
55
56 // create shared informer for Kubernetes APIs
57 var kubeconfig *rest.Config
58 var err error
59 if len(o.CoreAPIKubeconfigPath) > 0 {
60 loadingRules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: o.CoreAPIKubeconfigPath}
61 loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
62 kubeconfig, err = loader.ClientConfig()
63 if err != nil {
64 return fmt.Errorf("failed to load kubeconfig at %q: %v", o.CoreAPIKubeconfigPath, err)
65 }
66 } else {
67 kubeconfig, err = rest.InClusterConfig()
68 if err != nil {
69 return err
70 }
71 }
72 clientgoExternalClient, err := clientgoclientset.NewForConfig(kubeconfig)
73 if err != nil {
74 return fmt.Errorf("failed to create Kubernetes clientset: %v", err)
75 }
76 config.ClientConfig = kubeconfig
77 config.SharedInformerFactory = clientgoinformers.NewSharedInformerFactory(clientgoExternalClient, 10*time.Minute)
78
79 return nil
80}
81
82func (o *CoreAPIOptions) Validate() []error {
83 return nil
84}