-
Notifications
You must be signed in to change notification settings - Fork 103
/
utils.go
337 lines (307 loc) · 10.7 KB
/
utils.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 2019-2024 The Liqo 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 utils
import (
"errors"
"fmt"
"net"
"net/netip"
"os"
"strings"
"time"
"go4.org/netipx"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
netv1alpha1 "github.com/liqotech/liqo/apis/net/v1alpha1"
"github.com/liqotech/liqo/pkg/consts"
liqoneterrors "github.com/liqotech/liqo/pkg/liqonet/errors"
)
// MapIPToNetwork creates a new IP address obtained by means of the old IP address and the new network.
func MapIPToNetwork(newNetwork, oldIP string) (newIP string, err error) {
if newNetwork == consts.DefaultCIDRValue {
return oldIP, nil
}
// Parse newNetwork
ip, network, err := net.ParseCIDR(newNetwork)
if err != nil {
return "", err
}
// Get mask
mask := network.Mask
// Get slice of bytes for newNetwork
// Type net.IP has underlying type []byte
parsedNewIP := ip.To4()
// Get oldIP as slice of bytes
parsedOldIP := net.ParseIP(oldIP)
if parsedOldIP == nil {
return "", fmt.Errorf("cannot parse oldIP")
}
parsedOldIP = parsedOldIP.To4()
// Substitute the last 32-mask bits of newNetwork with bits taken by the old ip
for i := 0; i < len(mask); i++ {
// Step 1: NOT(mask[i]) = mask[i] ^ 0xff. They are the 'host' bits
// Step 2: BITWISE AND between the host bits and parsedOldIP[i] zeroes the network bits in parsedOldIP[i]
// Step 3: BITWISE OR copies the result of step 2 in newIP[i]
parsedNewIP[i] |= (mask[i] ^ 0xff) & parsedOldIP[i]
}
newIP = parsedNewIP.String()
return
}
// GetPodName returns the pod name.
func GetPodName() (string, error) {
podName, isSet := os.LookupEnv("POD_NAME")
if !isSet || podName == "" {
return "", errors.New("pod name is not yet set")
}
return podName, nil
}
// GetPodIP returns the pod IP address.
func GetPodIP() (net.IP, error) {
ipAddress, isSet := os.LookupEnv("POD_IP")
if !isSet || ipAddress == "" {
return nil, errors.New("pod IP is not yet set")
}
return net.ParseIP(ipAddress), nil
}
// GetPodNamespace gets the namespace of the pod passed as an environment variable.
func GetPodNamespace() (string, error) {
namespace, isSet := os.LookupEnv("POD_NAMESPACE")
if !isSet || namespace == "" {
return "", errors.New("the POD_NAMESPACE environment variable is not set as an environment variable")
}
return namespace, nil
}
// GetNodeName gets the name of the node where the pod is running passed as an environment variable.
func GetNodeName() (string, error) {
nodeName, isSet := os.LookupEnv("NODE_NAME")
if !isSet || nodeName == "" {
return nodeName, errors.New("NODE_NAME environment variable has not been set. check you manifest file")
}
return nodeName, nil
}
// GetMask retrieves the mask from a CIDR.
func GetMask(network string) uint8 {
_, subnet, err := net.ParseCIDR(network)
utilruntime.Must(err)
ones, _ := subnet.Mask.Size()
return uint8(ones)
}
// SetMask forges a new cidr from a network cidr and a mask.
func SetMask(network string, mask uint8) string {
_, n, err := net.ParseCIDR(network)
utilruntime.Must(err)
newMask := net.CIDRMask(int(mask), 32)
n.Mask = newMask
return n.String()
}
// Next used to get the second half of a given network.
func Next(network string) string {
prefix, err := netip.ParsePrefix(network)
utilruntime.Must(err)
// Step 1: Get last IP address of network
// Step 2: Get next IP address
firstIP := netipx.RangeOfPrefix(prefix).To().Next()
prefix = netip.PrefixFrom(firstIP, prefix.Bits())
return prefix.String()
}
// GetPodCIDRS for a given tep the function retrieves the values for localPodCIDR and remotePodCIDR.
// Their values depend if the NAT is required or not.
func GetPodCIDRS(tep *netv1alpha1.TunnelEndpoint) (localRemappedPodCIDR, remotePodCIDR string) {
if tep.Spec.RemoteNATPodCIDR != consts.DefaultCIDRValue {
remotePodCIDR = tep.Spec.RemoteNATPodCIDR
} else {
remotePodCIDR = tep.Spec.RemotePodCIDR
}
localRemappedPodCIDR = tep.Spec.LocalNATPodCIDR
return localRemappedPodCIDR, remotePodCIDR
}
// GetExternalCIDRS for a given tep the function retrieves the values for localExternalCIDR and remoteExternalCIDR.
// Their values depend if the NAT is required or not.
func GetExternalCIDRS(tep *netv1alpha1.TunnelEndpoint) (localExternalCIDR, remoteExternalCIDR string) {
if tep.Spec.LocalNATExternalCIDR != consts.DefaultCIDRValue {
localExternalCIDR = tep.Spec.LocalNATExternalCIDR
} else {
localExternalCIDR = tep.Spec.LocalExternalCIDR
}
if tep.Spec.RemoteNATExternalCIDR != consts.DefaultCIDRValue {
remoteExternalCIDR = tep.Spec.RemoteNATExternalCIDR
} else {
remoteExternalCIDR = tep.Spec.RemoteExternalCIDR
}
return
}
// IsValidCIDR returns an error if the received CIDR is invalid.
func IsValidCIDR(cidr string) error {
_, _, err := net.ParseCIDR(cidr)
return err
}
// GetFirstIP returns the first IP address of a network.
func GetFirstIP(network string) (string, error) {
firstIP, _, err := net.ParseCIDR(network)
if err != nil {
return "", err
}
return firstIP.String(), nil
}
// GetTunnelIP returns the IP address of the tunnel, which is the first external CIDR ip.
func GetTunnelIP(externalCIDR string) (string, error) {
ipPrefix, err := netip.ParsePrefix(externalCIDR)
if err != nil {
return "", err
}
return ipPrefix.Addr().Next().String(), nil
}
// CheckTep checks validity of TunnelEndpoint resource fields.
func CheckTep(tep *netv1alpha1.TunnelEndpoint) error {
if tep.Spec.ClusterIdentity.ClusterID == "" {
return &liqoneterrors.WrongParameter{
Parameter: consts.ClusterIDLabelName,
Reason: liqoneterrors.StringNotEmpty,
}
}
if err := IsValidCIDR(tep.Spec.RemotePodCIDR); err != nil {
return &liqoneterrors.WrongParameter{
Parameter: consts.PodCIDR,
Reason: liqoneterrors.ValidCIDR,
}
}
if err := IsValidCIDR(tep.Spec.RemoteExternalCIDR); err != nil {
return &liqoneterrors.WrongParameter{
Parameter: consts.ExternalCIDR,
Reason: liqoneterrors.ValidCIDR,
}
}
if err := IsValidCIDR(tep.Spec.LocalPodCIDR); err != nil {
return &liqoneterrors.WrongParameter{
Parameter: consts.LocalPodCIDR,
Reason: liqoneterrors.ValidCIDR,
}
}
if err := IsValidCIDR(tep.Spec.LocalExternalCIDR); err != nil {
return &liqoneterrors.WrongParameter{
Parameter: consts.LocalExternalCIDR,
Reason: liqoneterrors.ValidCIDR,
}
}
if err := IsValidCIDR(tep.Spec.LocalNATPodCIDR); tep.Spec.LocalNATPodCIDR != consts.DefaultCIDRValue &&
err != nil {
return &liqoneterrors.WrongParameter{
Parameter: consts.LocalNATPodCIDR,
Reason: liqoneterrors.ValidCIDR,
}
}
if err := IsValidCIDR(tep.Spec.LocalNATExternalCIDR); tep.Spec.LocalNATExternalCIDR != consts.DefaultCIDRValue &&
err != nil {
return &liqoneterrors.WrongParameter{
Parameter: consts.LocalNATExternalCIDR,
Reason: liqoneterrors.ValidCIDR,
}
}
if err := IsValidCIDR(tep.Spec.RemoteNATPodCIDR); tep.Spec.RemoteNATPodCIDR != consts.DefaultCIDRValue &&
err != nil {
return &liqoneterrors.WrongParameter{
Parameter: consts.RemoteNATPodCIDR,
Reason: liqoneterrors.ValidCIDR,
}
}
if err := IsValidCIDR(tep.Spec.RemoteNATExternalCIDR); tep.Spec.RemoteNATExternalCIDR != consts.DefaultCIDRValue &&
err != nil {
return &liqoneterrors.WrongParameter{
Parameter: consts.RemoteNATExternalCIDR,
Reason: liqoneterrors.ValidCIDR,
}
}
return nil
}
// GetOverlayIP given an IP address it is mapped in to the overlay network,
// described by consts.OverlayNetworkPrefix. It uses the overlay prefix and the
// last three octets of the original IP address.
func GetOverlayIP(ip string) string {
addr := net.ParseIP(ip)
// If the ip is malformed we prevent a panic, the subsequent calls
// that use the returned value will return an error.
if addr == nil {
return ""
}
tokens := strings.Split(ip, ".")
return strings.Join([]string{consts.OverlayNetworkPrefix, tokens[1], tokens[2], tokens[3]}, ".")
}
// AddAnnotationToObj for a given object it adds the annotation with the given key and value.
// It return a bool which is true when the annotations has been added or false if the
// annotation is already present.
func AddAnnotationToObj(obj client.Object, aKey, aValue string) bool {
annotations := obj.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string, 1)
}
oldAnnValue, ok := annotations[aKey]
// If the annotations does not exist or is outdated then set it.
if !ok || oldAnnValue != aValue {
annotations[aKey] = aValue
obj.SetAnnotations(annotations)
return true
}
return false
}
// GetAnnotationValueFromObj for a given object it return the value of the label denoted by the
// given key. If the key does not exist it returns an empty string.
func GetAnnotationValueFromObj(obj client.Object, akey string) string {
if obj.GetAnnotations() == nil {
return ""
}
return obj.GetAnnotations()[akey]
}
// AddLabelToObj for a given object it adds the label with the given key and value.
// It return a bool which is true when the label has been added or false if the
// label is already present.
func AddLabelToObj(obj client.Object, labelKey, labelValue string) bool {
labels := obj.GetLabels()
if labels == nil {
labels = make(map[string]string, 1)
}
oldLabelValue, ok := labels[labelKey]
// If the labels does not exist or is outdated then set it.
if !ok || oldLabelValue != labelValue {
labels[labelKey] = labelValue
obj.SetLabels(labels)
return true
}
return false
}
// SplitNetwork returns the two halves that make up a given network.
func SplitNetwork(network string) []string {
halves := make([]string, 2)
// Get halves mask length.
mask := GetMask(network)
mask++
// Get first half CIDR.
halves[0] = SetMask(network, mask)
// Get second half CIDR.
halves[1] = Next(halves[0])
return halves
}
// FormatLatency returns a string representing the given latency in a human readable format.
func FormatLatency(latency time.Duration) string {
if latency == 0 {
return consts.NotApplicable
}
if latency.Milliseconds() > 0 {
return fmt.Sprintf("%dms", latency.Milliseconds())
}
return fmt.Sprintf("%dμs", latency.Microseconds())
}
// IsLocalNetworkConfig checks if the given network configuration is local.
func IsLocalNetworkConfig(networkConfig *netv1alpha1.NetworkConfig) bool {
return networkConfig.Labels[consts.ReplicationRequestedLabel] == "true"
}