forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
262 lines (223 loc) · 8.2 KB
/
util.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
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"fmt"
"net"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
utilnet "k8s.io/apimachinery/pkg/util/net"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
federationapi "k8s.io/kubernetes/federation/apis/federation"
fedclient "k8s.io/kubernetes/federation/client/clientset_generated/federation_clientset"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/rbac"
client "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
kubectlcmd "k8s.io/kubernetes/pkg/kubectl/cmd"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
const (
// KubeconfigSecretDataKey is the key name used in the secret to
// stores a cluster's credentials.
KubeconfigSecretDataKey = "kubeconfig"
// Used in and to create the kube-dns configmap storing the zone info
FedDomainMapKey = "federations"
KubeDnsConfigmapName = "kube-dns"
// DefaultFederationSystemNamespace is the namespace in which
// federation system components are hosted.
DefaultFederationSystemNamespace = "federation-system"
// Used to build a clientset for a cluster using the secret
userAgentName = "kubefed-tool"
KubeAPIQPS = 20.0
KubeAPIBurst = 30
rbacAPINotAvailable = "RBAC API not available"
)
// used to identify the rbac api availability error.
type NoRBACAPIError struct {
s string
}
func (n *NoRBACAPIError) Error() string {
return n.s
}
// AdminConfig provides a filesystem based kubeconfig (via
// `PathOptions()`) and a mechanism to talk to the federation
// host cluster and the federation control plane api server.
type AdminConfig interface {
// PathOptions provides filesystem based kubeconfig access.
PathOptions() *clientcmd.PathOptions
// FedClientSet provides a federation API compliant clientset
// to communicate with the federation control plane api server
FederationClientset(context, kubeconfigPath string) (*fedclient.Clientset, error)
// ClusterFactory provides a mechanism to communicate with the
// cluster derived from the context and the kubeconfig.
ClusterFactory(context, kubeconfigPath string) cmdutil.Factory
}
// adminConfig implements the AdminConfig interface.
type adminConfig struct {
pathOptions *clientcmd.PathOptions
}
// NewAdminConfig creates an admin config for `kubefed` commands.
func NewAdminConfig(pathOptions *clientcmd.PathOptions) AdminConfig {
return &adminConfig{
pathOptions: pathOptions,
}
}
func (a *adminConfig) PathOptions() *clientcmd.PathOptions {
return a.pathOptions
}
func (a *adminConfig) FederationClientset(context, kubeconfigPath string) (*fedclient.Clientset, error) {
fedConfig := a.getClientConfig(context, kubeconfigPath)
fedClientConfig, err := fedConfig.ClientConfig()
if err != nil {
return nil, err
}
return fedclient.NewForConfigOrDie(fedClientConfig), nil
}
func (a *adminConfig) ClusterFactory(context, kubeconfigPath string) cmdutil.Factory {
hostClientConfig := a.getClientConfig(context, kubeconfigPath)
return cmdutil.NewFactory(hostClientConfig)
}
func (a *adminConfig) getClientConfig(context, kubeconfigPath string) clientcmd.ClientConfig {
loadingRules := *a.pathOptions.LoadingRules
loadingRules.Precedence = a.pathOptions.GetLoadingPrecedence()
loadingRules.ExplicitPath = kubeconfigPath
overrides := &clientcmd.ConfigOverrides{
CurrentContext: context,
}
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(&loadingRules, overrides)
}
// SubcommandOptions holds the configuration required by the subcommands of
// `kubefed`.
type SubcommandOptions struct {
Name string
Host string
FederationSystemNamespace string
Kubeconfig string
}
func (o *SubcommandOptions) Bind(flags *pflag.FlagSet) {
flags.StringVar(&o.Kubeconfig, "kubeconfig", "", "Path to the kubeconfig file to use for CLI requests.")
flags.StringVar(&o.Host, "host-cluster-context", "", "Host cluster context")
flags.StringVar(&o.FederationSystemNamespace, "federation-system-namespace", DefaultFederationSystemNamespace, "Namespace in the host cluster where the federation system components are installed")
}
func (o *SubcommandOptions) SetName(cmd *cobra.Command, args []string) error {
name, err := kubectlcmd.NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
o.Name = name
return nil
}
func CreateKubeconfigSecret(clientset client.Interface, kubeconfig *clientcmdapi.Config, namespace, name string, dryRun bool) (*api.Secret, error) {
configBytes, err := clientcmd.Write(*kubeconfig)
if err != nil {
return nil, err
}
// Build the secret object with the minified and flattened
// kubeconfig content.
secret := &api.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Data: map[string][]byte{
KubeconfigSecretDataKey: configBytes,
},
}
if !dryRun {
return clientset.Core().Secrets(namespace).Create(secret)
}
return secret, nil
}
var kubeconfigGetterForSecret = func(secret *api.Secret) clientcmd.KubeconfigGetter {
return func() (*clientcmdapi.Config, error) {
var data []byte
ok := false
data, ok = secret.Data[KubeconfigSecretDataKey]
if !ok {
return nil, fmt.Errorf("secret does not have data with key: %s", KubeconfigSecretDataKey)
}
return clientcmd.Load(data)
}
}
func GetClientsetFromSecret(secret *api.Secret, serverAddress string) (*client.Clientset, error) {
clusterConfig, err := buildConfigFromSecret(secret, serverAddress)
if err == nil && clusterConfig != nil {
clientset := client.NewForConfigOrDie(restclient.AddUserAgent(clusterConfig, userAgentName))
return clientset, nil
}
return nil, err
}
func GetServerAddress(c *federationapi.Cluster) (string, error) {
hostIP, err := utilnet.ChooseHostInterface()
if err != nil {
return "", err
}
for _, item := range c.Spec.ServerAddressByClientCIDRs {
_, cidrnet, err := net.ParseCIDR(item.ClientCIDR)
if err != nil {
return "", err
}
if cidrnet.Contains(hostIP) {
return item.ServerAddress, nil
}
}
return "", nil
}
func buildConfigFromSecret(secret *api.Secret, serverAddress string) (*restclient.Config, error) {
kubeconfigGetter := kubeconfigGetterForSecret(secret)
clusterConfig, err := clientcmd.BuildConfigFromKubeconfigGetter(serverAddress, kubeconfigGetter)
if err != nil {
return nil, err
}
clusterConfig.QPS = KubeAPIQPS
clusterConfig.Burst = KubeAPIBurst
return clusterConfig, nil
}
// GetVersionedClientForRBACOrFail discovers the versioned rbac APIs and gets the versioned
// clientset for either the preferred version or the first listed version (if no preference listed)
// TODO: We need to evaluate the usage of RESTMapper interface to achieve te same functionality
func GetVersionedClientForRBACOrFail(hostFactory cmdutil.Factory) (client.Interface, error) {
discoveryclient, err := hostFactory.DiscoveryClient()
if err != nil {
return nil, err
}
groupList, err := discoveryclient.ServerGroups()
if err != nil {
return nil, fmt.Errorf("Couldn't get clientset to create RBAC roles in the host cluster: %v", err)
}
for _, g := range groupList.Groups {
if g.Name == rbac.GroupName {
if g.PreferredVersion.GroupVersion != "" {
gv, err := schema.ParseGroupVersion(g.PreferredVersion.GroupVersion)
if err != nil {
return nil, err
}
return hostFactory.ClientSetForVersion(&gv)
}
for i := 0; i < len(g.Versions); i++ {
if g.Versions[i].GroupVersion != "" {
gv, err := schema.ParseGroupVersion(g.Versions[i].GroupVersion)
if err != nil {
return nil, err
}
return hostFactory.ClientSetForVersion(&gv)
}
}
}
}
return nil, &NoRBACAPIError{rbacAPINotAvailable}
}