/
proxy.go
188 lines (155 loc) · 5.73 KB
/
proxy.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
/*
Copyright 2019 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 cluster
import (
"fmt"
"strings"
"github.com/pkg/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/discovery"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/cluster-api/cmd/clusterctl/internal/scheme"
"sigs.k8s.io/cluster-api/cmd/version"
"sigs.k8s.io/controller-runtime/pkg/client"
)
var (
Scheme = scheme.Scheme
)
type proxy struct {
kubeconfig string
}
var _ Proxy = &proxy{}
func (k *proxy) CurrentNamespace() (string, error) {
config, err := clientcmd.LoadFromFile(k.kubeconfig)
if err != nil {
return "", errors.Wrapf(err, "failed to load Kubeconfig file from %q", k.kubeconfig)
}
if config.CurrentContext == "" {
return "", errors.Wrapf(err, "failed to get current-context from %q", k.kubeconfig)
}
v, ok := config.Contexts[config.CurrentContext]
if !ok {
return "", errors.Wrapf(err, "failed to get context %q from %q", config.CurrentContext, k.kubeconfig)
}
if v.Namespace != "" {
return v.Namespace, nil
}
return "default", nil
}
func (k *proxy) NewClient() (client.Client, error) {
config, err := k.getConfig()
if err != nil {
return nil, err
}
c, err := client.New(config, client.Options{Scheme: Scheme})
if err != nil {
return nil, errors.Wrap(err, "failed to connect to the management cluster")
}
return c, nil
}
func (k *proxy) ListResources(labels map[string]string, namespaces ...string) ([]unstructured.Unstructured, error) {
cs, err := k.newClientSet()
if err != nil {
return nil, err
}
c, err := k.NewClient()
if err != nil {
return nil, err
}
// Get all the API resources in the cluster.
resourceList, err := cs.Discovery().ServerPreferredResources()
if err != nil {
return nil, errors.Wrap(err, "failed to list api resources")
}
// Select resources with list and delete methods (list is required by this method, delete by the callers of this method)
resourceList = discovery.FilteredBy(discovery.SupportsAllVerbs{Verbs: []string{"list", "delete"}}, resourceList)
var ret []unstructured.Unstructured
for _, resourceGroup := range resourceList {
for _, resourceKind := range resourceGroup.APIResources {
// Discard the resourceKind that exists in two api groups (we are excluding one of the two groups arbitrarily).
if resourceGroup.GroupVersion == "extensions/v1beta1" &&
(resourceKind.Name == "daemonsets" || resourceKind.Name == "deployments" || resourceKind.Name == "replicasets" || resourceKind.Name == "networkpolicies" || resourceKind.Name == "ingresses") {
continue
}
// List all the object instances of this resourceKind with the given labels
if resourceKind.Namespaced {
for _, namespace := range namespaces {
objList, err := listObjByGVK(c, resourceGroup.GroupVersion, resourceKind.Kind, []client.ListOption{client.MatchingLabels(labels), client.InNamespace(namespace)})
if err != nil {
return nil, err
}
ret = append(ret, objList.Items...)
}
} else {
objList, err := listObjByGVK(c, resourceGroup.GroupVersion, resourceKind.Kind, []client.ListOption{client.MatchingLabels(labels)})
if err != nil {
return nil, err
}
ret = append(ret, objList.Items...)
}
}
}
return ret, nil
}
func listObjByGVK(c client.Client, groupVersion, kind string, options []client.ListOption) (*unstructured.UnstructuredList, error) {
objList := new(unstructured.UnstructuredList)
objList.SetAPIVersion(groupVersion)
objList.SetKind(kind)
if err := c.List(ctx, objList, options...); err != nil {
if !apierrors.IsNotFound(err) {
return nil, errors.Wrapf(err, "failed to list objects for the %q GroupVersionKind", objList.GroupVersionKind())
}
}
return objList, nil
}
func newProxy(kubeconfig string) Proxy {
// If a kubeconfig file isn't provided, find one in the standard locations.
if kubeconfig == "" {
kubeconfig = clientcmd.NewDefaultClientConfigLoadingRules().GetDefaultFilename()
}
return &proxy{
kubeconfig: kubeconfig,
}
}
func (k *proxy) getConfig() (*rest.Config, error) {
config, err := clientcmd.LoadFromFile(k.kubeconfig)
if err != nil {
return nil, errors.Wrapf(err, "failed to load Kubeconfig file from %q", k.kubeconfig)
}
restConfig, err := clientcmd.NewDefaultClientConfig(*config, &clientcmd.ConfigOverrides{}).ClientConfig()
if err != nil {
if strings.HasPrefix(err.Error(), "invalid configuration:") {
return nil, errors.New(strings.Replace(err.Error(), "invalid configuration:", "invalid kubeconfig file; clusterctl requires a valid kubeconfig file to connect to the management cluster:", 1))
}
return nil, err
}
restConfig.UserAgent = fmt.Sprintf("clusterctl/%s (%s)", version.Get().GitVersion, version.Get().Platform)
// Set QPS and Burst to a threshold that ensures the controller runtime client/client go does't generate throttling log messages
restConfig.QPS = 20
restConfig.Burst = 100
return restConfig, nil
}
func (k *proxy) newClientSet() (*kubernetes.Clientset, error) {
config, err := k.getConfig()
if err != nil {
return nil, err
}
cs, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, errors.Wrap(err, "failed to create the client-go client")
}
return cs, nil
}