/
init.go
281 lines (237 loc) · 8.94 KB
/
init.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
// Copyright 2016-2020 Authors of Cilium
//
// 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 abstracts all Kubernetes specific behaviour
package k8s
import (
"context"
"fmt"
"time"
"github.com/cilium/cilium/pkg/backoff"
"github.com/cilium/cilium/pkg/controller"
ipamOption "github.com/cilium/cilium/pkg/ipam/option"
cilium_v2_client "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2/client"
k8sconfig "github.com/cilium/cilium/pkg/k8s/config"
k8sConst "github.com/cilium/cilium/pkg/k8s/constants"
slim_corev1 "github.com/cilium/cilium/pkg/k8s/slim/k8s/apis/core/v1"
k8sversion "github.com/cilium/cilium/pkg/k8s/version"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/node"
nodeTypes "github.com/cilium/cilium/pkg/node/types"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/source"
"github.com/sirupsen/logrus"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
nodeRetrievalMaxRetries = 15
)
func waitForNodeInformation(ctx context.Context, nodeName string) *nodeTypes.Node {
backoff := backoff.Exponential{
Min: time.Duration(200) * time.Millisecond,
Factor: 2.0,
Name: "k8s-node-retrieval",
}
for retry := 0; retry < nodeRetrievalMaxRetries; retry++ {
n, err := retrieveNodeInformation(nodeName)
if err != nil {
log.WithError(err).Warning("Waiting for k8s node information")
backoff.Wait(ctx)
continue
}
return n
}
return nil
}
func retrieveNodeInformation(nodeName string) (*nodeTypes.Node, error) {
requireIPv4CIDR := option.Config.K8sRequireIPv4PodCIDR
requireIPv6CIDR := option.Config.K8sRequireIPv6PodCIDR
// At this point it's not clear whether the device auto-detection will
// happen, as initKubeProxyReplacementOptions() might disable BPF NodePort.
// Anyway, to be on the safe side, don't give up waiting for a (Cilium)Node
// self object.
mightAutoDetectDevices := option.MightAutoDetectDevices()
var n *nodeTypes.Node
if option.Config.IPAM == ipamOption.IPAMOperator {
ciliumNode, err := CiliumClient().CiliumV2().CiliumNodes().Get(context.TODO(), nodeName, v1.GetOptions{})
if err != nil {
// If no CIDR is required, retrieving the node information is
// optional
if !requireIPv4CIDR && !requireIPv6CIDR && !mightAutoDetectDevices {
return nil, nil
}
return nil, fmt.Errorf("unable to retrieve k8s node information: %s", err)
}
no := nodeTypes.ParseCiliumNode(ciliumNode)
n = &no
log.WithField(logfields.NodeName, n.Name).Info("Retrieved node information from cilium node")
} else {
k8sNode, err := GetNode(Client(), nodeName)
if err != nil {
// If no CIDR is required, retrieving the node information is
// optional
if !requireIPv4CIDR && !requireIPv6CIDR && !mightAutoDetectDevices {
return nil, nil
}
return nil, fmt.Errorf("unable to retrieve k8s node information: %s", err)
}
nodeInterface := ConvertToNode(k8sNode)
if nodeInterface == nil {
// This will never happen and the GetNode on line 63 will be soon
// make a request from the local store instead.
return nil, fmt.Errorf("invalid k8s node: %s", k8sNode)
}
typesNode := nodeInterface.(*slim_corev1.Node)
// The source is left unspecified as this node resource should never be
// used to update state
n = ParseNode(typesNode, source.Unspec)
log.WithField(logfields.NodeName, n.Name).Info("Retrieved node information from kubernetes node")
}
if requireIPv4CIDR && n.IPv4AllocCIDR == nil {
return nil, fmt.Errorf("required IPv4 pod CIDR not present in node resource")
}
if requireIPv6CIDR && n.IPv6AllocCIDR == nil {
return nil, fmt.Errorf("required IPv6 pod CIDR not present in node resource")
}
return n, nil
}
// useNodeCIDR sets the ipv4-range and ipv6-range values values from the
// addresses defined in the given node.
func useNodeCIDR(n *nodeTypes.Node) {
if n.IPv4AllocCIDR != nil && option.Config.EnableIPv4 {
node.SetIPv4AllocRange(n.IPv4AllocCIDR)
}
if n.IPv6AllocCIDR != nil && option.Config.EnableIPv6 {
node.SetIPv6NodeRange(n.IPv6AllocCIDR.IPNet)
}
}
// Init initializes the Kubernetes package. It is required to call Configure()
// beforehand.
func Init(conf k8sconfig.Configuration) error {
k8sRestClient, closeAllDefaultClientConns, err := createDefaultClient()
if err != nil {
return fmt.Errorf("unable to create k8s client: %s", err)
}
closeAllCiliumClientConns, err := createDefaultCiliumClient()
if err != nil {
return fmt.Errorf("unable to create cilium k8s client: %s", err)
}
heartBeat := func(ctx context.Context) error {
// Kubernetes does a get node of the node that kubelet is running [0]. This seems excessive in
// our case because the amount of data transferred is bigger than doing a Get of /healthz.
// For this reason we have picked to perform a get on `/healthz` instead a get of a node.
//
// [0] https://github.com/kubernetes/kubernetes/blob/v1.17.3/pkg/kubelet/kubelet_node_status.go#L423
res := k8sRestClient.Get().Resource("healthz").Do(ctx)
return res.Error()
}
if option.Config.K8sHeartbeatTimeout != 0 {
controller.NewManager().UpdateController("k8s-heartbeat",
controller.ControllerParams{
DoFunc: func(context.Context) error {
runHeartbeat(
heartBeat,
option.Config.K8sHeartbeatTimeout,
closeAllDefaultClientConns,
closeAllCiliumClientConns,
)
return nil
},
RunInterval: option.Config.K8sHeartbeatTimeout,
},
)
}
if err := k8sversion.Update(Client(), conf); err != nil {
return err
}
if !k8sversion.Capabilities().MinimalVersionMet {
return fmt.Errorf("k8s version (%v) is not meeting the minimal requirement (%v)",
k8sversion.Version(), k8sversion.MinimalVersionConstraint)
}
return nil
}
// GetNodeSpec retrieves this node spec from kubernetes. This node information
// can either be derived from a CiliumNode or a Kubernetes node.
func GetNodeSpec() error {
// Use of the environment variable overwrites the node-name
// automatically derived
nodeName := nodeTypes.GetName()
if nodeName == "" {
if option.Config.K8sRequireIPv4PodCIDR || option.Config.K8sRequireIPv6PodCIDR {
return fmt.Errorf("node name must be specified via environment variable '%s' to retrieve Kubernetes PodCIDR range", k8sConst.EnvNodeNameSpec)
}
if option.MightAutoDetectDevices() {
log.Info("K8s node name is empty. BPF NodePort might not be able to auto detect all devices")
}
return nil
}
if n := waitForNodeInformation(context.TODO(), nodeName); n != nil {
nodeIP4 := n.GetNodeIP(false)
nodeIP6 := n.GetNodeIP(true)
k8sNodeIP := n.GetK8sNodeIP()
log.WithFields(logrus.Fields{
logfields.NodeName: n.Name,
logfields.Labels: logfields.Repr(n.Labels),
logfields.IPAddr + ".ipv4": nodeIP4,
logfields.IPAddr + ".ipv6": nodeIP6,
logfields.V4Prefix: n.IPv4AllocCIDR,
logfields.V6Prefix: n.IPv6AllocCIDR,
logfields.K8sNodeIP: k8sNodeIP,
}).Info("Received own node information from API server")
useNodeCIDR(n)
// Note: Node IPs are derived regardless of
// option.Config.EnableIPv4 and
// option.Config.EnableIPv6. This is done to enable
// underlay addressing to be different from overlay
// addressing, e.g. an IPv6 only PodCIDR running over
// IPv4 encapsulation.
if nodeIP4 != nil {
node.SetExternalIPv4(nodeIP4)
}
if nodeIP6 != nil {
node.SetIPv6(nodeIP6)
}
node.SetLabels(n.Labels)
// K8s Node IP is used by BPF NodePort devices auto-detection
node.SetK8sNodeIP(k8sNodeIP)
} else {
// if node resource could not be received, fail if
// PodCIDR requirement has been requested
if option.Config.K8sRequireIPv4PodCIDR || option.Config.K8sRequireIPv6PodCIDR {
log.Fatal("Unable to derive PodCIDR from Kubernetes node resource, giving up")
}
}
// Annotate addresses will occur later since the user might
// want to specify them manually
return nil
}
// RegisterCRDs registers all CRDs
func RegisterCRDs() error {
if option.Config.SkipCRDCreation {
return nil
}
restConfig, err := CreateConfig()
if err != nil {
return fmt.Errorf("Unable to create rest configuration: %s", err)
}
apiextensionsclientset, err := apiextensionsclient.NewForConfig(restConfig)
if err != nil {
return fmt.Errorf("Unable to create rest configuration for k8s CRD: %s", err)
}
err = cilium_v2_client.CreateCustomResourceDefinitions(apiextensionsclientset)
if err != nil {
return fmt.Errorf("Unable to create custom resource definition: %s", err)
}
return nil
}