forked from projectcalico/libcalico-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k8s.go
337 lines (297 loc) · 10.9 KB
/
k8s.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
// Copyright (c) 2016 Tigera, Inc. All rights reserved.
// 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 k8s
import (
goerrors "errors"
log "github.com/Sirupsen/logrus"
"github.com/projectcalico/libcalico-go/lib/backend/api"
"github.com/projectcalico/libcalico-go/lib/backend/model"
"github.com/projectcalico/libcalico-go/lib/errors"
k8sapi "k8s.io/kubernetes/pkg/api"
clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
)
type KubeClient struct {
clientSet *clientset.Clientset
converter converter
}
type KubeConfig struct {
Kubeconfig string `json:"kubeconfig" envconfig:"KUBECONFIG" default:""`
K8sAPIEndpoint string `json:"k8sAPIEndpoint" envconfig:"K8S_API_ENDPOINT" default:""`
K8sKeyFile string `json:"k8sKeyFile" envconfig:"K8S_KEY_FILE" default:""`
K8sCertFile string `json:"k8sCertFile" envconfig:"K8S_CERT_FILE" default:""`
K8sCAFile string `json:"k8sCAFile" envconfig:"K8S_CA_FILE" default:""`
K8sAPIToken string `json:"k8sAPIToken" envconfig:"K8S_API_TOKEN" default:""`
}
func NewKubeClient(kc *KubeConfig) (*KubeClient, error) {
// Use the kubernetes client code to load the kubeconfig file and combine it with the overrides.
log.Infof("Building client for config: %+v", kc)
configOverrides := &clientcmd.ConfigOverrides{}
var overridesMap = []struct {
variable *string
value string
}{
{&configOverrides.ClusterInfo.Server, kc.K8sAPIEndpoint},
{&configOverrides.AuthInfo.ClientCertificate, kc.K8sCertFile},
{&configOverrides.AuthInfo.ClientKey, kc.K8sKeyFile},
{&configOverrides.ClusterInfo.CertificateAuthority, kc.K8sCAFile},
{&configOverrides.AuthInfo.Token, kc.K8sAPIToken},
}
// Set an explicit path to the kubeconfig if one
// was provided.
loadingRules := clientcmd.ClientConfigLoadingRules{}
if kc.Kubeconfig != "" {
loadingRules.ExplicitPath = kc.Kubeconfig
}
// Using the override map above, populate any non-empty values.
for _, override := range overridesMap {
if override.value != "" {
*override.variable = override.value
}
}
log.Infof("Config overrides: %+v", configOverrides)
// A kubeconfig file was provided. Use it to load a config, passing through
// any overrides.
config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&loadingRules, configOverrides).ClientConfig()
if err != nil {
return nil, err
}
// Create the clientset
cs, err := clientset.NewForConfig(config)
if err != nil {
return nil, err
}
log.Debugf("Created k8s clientSet: %+v", cs)
return &KubeClient{clientSet: cs}, nil
}
func (c *KubeClient) Syncer(callbacks api.SyncerCallbacks) api.Syncer {
return newSyncer(*c, callbacks)
}
// Create an entry in the datastore. This errors if the entry already exists.
func (c *KubeClient) Create(d *model.KVPair) (*model.KVPair, error) {
log.Warn("Attempt to 'Create' using kubernetes backend is not supported.")
return nil, errors.ErrorResourceDoesNotExist{
Err: goerrors.New("Resource does not exist"),
Identifier: d.Key,
}
}
// Update an existing entry in the datastore. This errors if the entry does
// not exist.
func (c *KubeClient) Update(d *model.KVPair) (*model.KVPair, error) {
// This is a noop. Calico components shouldn't be modifying
// k8s resources.
log.Infof("Kubernetes backend received 'Update' for %+v - do nothing.", d.Key)
return d, nil
}
// Set an existing entry in the datastore. This ignores whether an entry already
// exists.
func (c *KubeClient) Apply(d *model.KVPair) (*model.KVPair, error) {
log.Infof("Ignoring 'Apply' for %s", d.Key)
return d, nil
}
// Delete an entry in the datastore. This is a no-op when using the k8s backend.
func (c *KubeClient) Delete(d *model.KVPair) error {
log.Warn("Attempt to 'Delete' using kubernetes backend is not supported.")
return nil
}
// Get an entry from the datastore. This errors if the entry does not exist.
func (c *KubeClient) Get(k model.Key) (*model.KVPair, error) {
log.Debugf("Received 'Get' request for %+v", k)
switch k.(type) {
case model.ProfileKey:
return c.getProfile(k.(model.ProfileKey))
case model.WorkloadEndpointKey:
return c.getWorkloadEndpoint(k.(model.WorkloadEndpointKey))
case model.PolicyKey:
return c.getPolicy(k.(model.PolicyKey))
case model.HostConfigKey:
return c.getHostConfig(k.(model.HostConfigKey))
case model.GlobalConfigKey:
return c.getGlobalConfig(k.(model.GlobalConfigKey))
case model.ReadyFlagKey:
return c.getReadyStatus(k.(model.ReadyFlagKey))
default:
return nil, errors.ErrorResourceDoesNotExist{
Err: goerrors.New("Resource does not exist"),
Identifier: k,
}
}
}
// List entries in the datastore. This may return an empty list of there are
// no entries matching the request in the ListInterface.
func (c *KubeClient) List(l model.ListInterface) ([]*model.KVPair, error) {
log.Debugf("Received 'List' request for %+v", l)
switch l.(type) {
case model.ProfileListOptions:
return c.listProfiles(l.(model.ProfileListOptions))
case model.WorkloadEndpointListOptions:
return c.listWorkloadEndpoints(l.(model.WorkloadEndpointListOptions))
case model.PolicyListOptions:
return c.listPolicies(l.(model.PolicyListOptions))
case model.GlobalConfigListOptions:
return c.listGlobalConfig(l.(model.GlobalConfigListOptions))
case model.HostConfigListOptions:
return c.listHostConfig(l.(model.HostConfigListOptions))
default:
return []*model.KVPair{}, nil
}
}
// listProfiles lists Profiles from the k8s API based on existing Namespaces.
func (c *KubeClient) listProfiles(l model.ProfileListOptions) ([]*model.KVPair, error) {
// If a name is specified, then do an exact lookup.
if l.Name != "" {
kvp, err := c.getProfile(model.ProfileKey{Name: l.Name})
if err != nil {
return []*model.KVPair{}, nil
}
return []*model.KVPair{kvp}, nil
}
// Otherwise, enumerate all.
namespaces, err := c.clientSet.Namespaces().List(k8sapi.ListOptions{})
if err != nil {
return nil, err
}
// For each Namespace, return a profile.
ret := []*model.KVPair{}
for _, ns := range namespaces.Items {
kvp, err := c.converter.namespaceToProfile(&ns)
if err != nil {
return nil, err
}
ret = append(ret, kvp)
}
return ret, nil
}
// getProfile gets the Profile from the k8s API based on existing Namespaces.
func (c *KubeClient) getProfile(k model.ProfileKey) (*model.KVPair, error) {
if k.Name == "" {
return nil, goerrors.New("Missing profile name")
}
namespaceName, err := c.converter.parseProfileName(k.Name)
if err != nil {
return nil, err
}
namespace, err := c.clientSet.Namespaces().Get(namespaceName)
if err != nil {
return nil, err
}
return c.converter.namespaceToProfile(namespace)
}
// listWorkloadEndpoints lists WorkloadEndpoints from the k8s API based on existing Pods.
func (c *KubeClient) listWorkloadEndpoints(l model.WorkloadEndpointListOptions) ([]*model.KVPair, error) {
// If a workload is provided, we can do an exact lookup of this
// workload endpoint.
if l.WorkloadID != "" {
kvp, err := c.getWorkloadEndpoint(model.WorkloadEndpointKey{
WorkloadID: l.WorkloadID,
})
if err != nil {
// Error getting the endpoint.
return nil, err
}
if kvp == nil {
// The workload endpoint doesn't exist.
return nil, nil
}
return []*model.KVPair{kvp}, nil
}
// Otherwise, enumerate all pods in all namespaces.
// We don't yet support hostname, orchestratorID, for the k8s backend.
pods, err := c.clientSet.Pods("").List(k8sapi.ListOptions{})
if err != nil {
return nil, err
}
// For each Pod, return a workload endpoint.
ret := []*model.KVPair{}
for _, pod := range pods.Items {
// Decide if this pod should be displayed.
if !c.converter.isCalicoPod(&pod) {
continue
}
kvp, err := c.converter.podToWorkloadEndpoint(&pod)
if err != nil {
return nil, err
}
ret = append(ret, kvp)
}
return ret, nil
}
// getWorkloadEndpoint gets the WorkloadEndpoint from the k8s API based on existing Pods.
func (c *KubeClient) getWorkloadEndpoint(k model.WorkloadEndpointKey) (*model.KVPair, error) {
// The workloadID is of the form namespace.podname. Parse it so we
// can find the correct namespace to get the pod.
namespace, podName := c.converter.parseWorkloadID(k.WorkloadID)
pod, err := c.clientSet.Pods(namespace).Get(podName)
if err != nil {
return nil, err
}
// Decide if this pod should be displayed.
if !c.converter.isCalicoPod(pod) {
return nil, nil
}
return c.converter.podToWorkloadEndpoint(pod)
}
// listPolicies lists the Policies from the k8s API based on NetworkPolicy objects.
func (c *KubeClient) listPolicies(l model.PolicyListOptions) ([]*model.KVPair, error) {
if l.Name != "" {
// Exact lookup on a NetworkPolicy.
kvp, err := c.getPolicy(model.PolicyKey{Name: l.Name})
if err != nil {
return []*model.KVPair{}, nil
}
return []*model.KVPair{kvp}, nil
}
// Otherwise, list all NetworkPolicy objects in all Namespaces.
networkPolicies, err := c.clientSet.NetworkPolicies("").List(k8sapi.ListOptions{})
if err != nil {
return nil, err
}
// For each policy, turn it into a Policy and generate the list.
ret := []*model.KVPair{}
for _, p := range networkPolicies.Items {
kvp, err := c.converter.networkPolicyToPolicy(&p)
if err != nil {
return nil, err
}
ret = append(ret, kvp)
}
return ret, nil
}
// getPolicy gets the Policy from the k8s API based on NetworkPolicy objects.
func (c *KubeClient) getPolicy(k model.PolicyKey) (*model.KVPair, error) {
if k.Name == "" {
return nil, goerrors.New("Missing policy name")
}
namespace, policyName := c.converter.parsePolicyName(k.Name)
networkPolicy, err := c.clientSet.NetworkPolicies(namespace).Get(policyName)
if err != nil {
return nil, err
}
return c.converter.networkPolicyToPolicy(networkPolicy)
}
func (c *KubeClient) getReadyStatus(k model.ReadyFlagKey) (*model.KVPair, error) {
return &model.KVPair{Key: k, Value: true}, nil
}
func (c *KubeClient) getGlobalConfig(k model.GlobalConfigKey) (*model.KVPair, error) {
return nil, goerrors.New("Get for GlobalConfig not supported in kubernetes backend")
}
func (c *KubeClient) listGlobalConfig(l model.GlobalConfigListOptions) ([]*model.KVPair, error) {
return []*model.KVPair{}, nil
}
func (c *KubeClient) getHostConfig(k model.HostConfigKey) (*model.KVPair, error) {
return nil, goerrors.New("Get for HostConfig not supported in kubernetes backend")
}
func (c *KubeClient) listHostConfig(l model.HostConfigListOptions) ([]*model.KVPair, error) {
return []*model.KVPair{}, nil
}