forked from projectcalico/calico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
felixconfig.go
386 lines (344 loc) · 12.1 KB
/
felixconfig.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// Copyright (c) 2017 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 migrator
import (
"fmt"
"reflect"
"strconv"
"strings"
"time"
log "github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
apiv3 "github.com/projectcalico/api/pkg/apis/projectcalico/v3"
"github.com/dtest11/calico/libcalico-go/lib/backend/model"
"github.com/dtest11/calico/libcalico-go/lib/net"
"github.com/dtest11/calico/libcalico-go/lib/upgrade/converters"
)
// Query the v1 format of GlobalConfigList and convert to the v3 format of
// FelixConfiguration and ClusterInformation.
func (m *migrationHelper) queryAndConvertFelixConfigV1ToV3(
data *MigrationData,
) error {
// Query all of the global config into a slice of KVPairs.
m.statusBullet("handling FelixConfiguration (global) resource")
kvps, err := m.clientv1.List(model.GlobalConfigListOptions{})
if err != nil {
return fmt.Errorf("error querying FelixConfiguration: %v", err)
}
// Parse the separate KVPairs into a global FelixConfiguration resource and a
// global ClusterInformation resource. Note that if this is KDD we set the Ready
// flag to true, otherwise to false.
globalConfig := apiv3.NewFelixConfiguration()
globalConfig.Name = "default"
if err := m.parseFelixConfigV1IntoResourceV3(kvps, globalConfig, data); err != nil {
return fmt.Errorf("error converting FelixConfiguration: %v", err)
}
m.statusBullet("handling ClusterInformation (global) resource")
clusterInfo := apiv3.NewClusterInformation()
clusterInfo.Name = "default"
if err = m.parseFelixConfigV1IntoResourceV3(kvps, clusterInfo, data); err != nil {
return fmt.Errorf("error converting ClusterInformation: %v", err)
}
// Update the ready flag in the resource based on the datastore type. For KDD the ready
// flag should be true, for etcd it should be false.
ready := m.clientv1.IsKDD()
clusterInfo.Spec.DatastoreReady = &ready
if m.clientv1.IsKDD() {
m.statusBullet("skipping FelixConfiguration (per-node) resources - not supported")
} else {
// Query all of the per-host felix config into a slice of KVPairs.
m.statusBullet("handling FelixConfiguration (per-node) resources")
kvps, err = m.clientv1.List(model.HostConfigListOptions{})
if err != nil {
return fmt.Errorf("error querying FelixConfiguration: %v", err)
}
// Sort the configuration into slices of KVPairs for each node, converting the
// nodename as we go.
nodeKvps := make(map[string][]*model.KVPair, 0)
for _, kvp := range kvps {
// Extract the key, update it and store the updated key. Store in the node-specific
// bucket.
hk := kvp.Key.(model.HostConfigKey)
hk.Hostname = converters.ConvertNodeName(hk.Hostname)
kvp.Key = hk
nodeKvps[hk.Hostname] = append(nodeKvps[hk.Hostname], kvp)
}
// For each node, get the felix config kvps and convert to v3 per-node
// FelixConfiguration resource.
for node, kvps := range nodeKvps {
// Convert to v3 resource.
nodeConfig := apiv3.NewFelixConfiguration()
nodeConfig.Name = fmt.Sprintf("node.%s", node)
if err := m.parseFelixConfigV1IntoResourceV3(kvps, nodeConfig, data); err != nil {
return fmt.Errorf("error converting FelixConfiguration: %v", err)
}
}
}
return nil
}
// This function converts a slice of v1 KVPairs into the appropriate v3 values and
// merges the results into a single v3 resource Spec for felix configuration (global
// or per host) or a clusterInfo.
// Conversion errors are added to the MigrationData struct.
func (m *migrationHelper) parseFelixConfigV1IntoResourceV3(
kvps []*model.KVPair,
res converters.Resource,
data *MigrationData,
) error {
logCxtRes := log.WithFields(log.Fields{
"kind": res.GetObjectKind().GroupVersionKind().Kind,
"name": res.GetObjectMeta().GetName(),
})
// Convert the KVP slice into a name value map.
keysv1 := map[string]model.Key{}
configv1 := map[string]string{}
for _, kvp := range kvps {
if kvp.Value == nil {
continue
}
switch key := kvp.Key.(type) {
case model.GlobalConfigKey:
configv1[key.Name] = kvp.Value.(string)
keysv1[key.Name] = key
case model.HostConfigKey:
configv1[key.Name] = kvp.Value.(string)
keysv1[key.Name] = key
}
}
// Extract the Spec from the resource FelixConfiguration or ClusterInfo.
specValue := reflect.ValueOf(res).Elem().FieldByName("Spec")
if !specValue.IsValid() {
return fmt.Errorf("unable to process config resource type: %v", res)
}
// Loop through the Spec setting each field from the supplied KVPair data.
setField := false
specType := specValue.Type()
for i := 0; i < specType.NumField(); i++ {
field := specType.Field(i)
fieldValue := specValue.Field(i)
// Get the v1 config value associated with the field.
configName := m.getConfigName(field)
logCxt := logCxtRes.WithFields(log.Fields{
"field": field.Name,
"configName": configName,
})
configStrValue, ok := configv1[configName]
if !ok {
logCxt.Debug("config value is not configured in v1")
continue
}
isPtr := field.Type.Kind() == reflect.Ptr
fieldName := field.Name
switch {
case strings.HasPrefix(fieldName, "Failsafe"):
// Special-case the Failsafe ports - these require parsing and settings as a struct.
if configStrValue == "none" {
// Has no failsafe ports
vProtoPort := &[]apiv3.ProtoPort{}
fieldValue.Set(reflect.ValueOf(vProtoPort))
setField = true
continue
}
vProtoPort, err := m.parseProtoPort(configStrValue)
if err != nil {
logCxt.WithError(err).Info("Failed to parse field")
data.ConversionErrors = append(data.ConversionErrors, ConversionError{
Cause: err,
KeyV1: keysv1[configName],
ValueV1: configStrValue,
KeyV3: resourceToKey(res),
})
continue
}
fieldValue.Set(reflect.ValueOf(vProtoPort)) // pointer to proto port slice.
setField = true
continue
case strings.HasPrefix(fieldName, "LogSeverity"):
// The log level fields need to have their value converted to the appropriate v3 value,
// but other than that are treated as normal string fields.
configStrValue = convertLogLevel(configStrValue)
}
_, ok = fieldValue.Interface().(*metav1.Duration)
if ok {
if duration, err := strconv.ParseFloat(configStrValue, 64); err != nil {
logCxt.WithError(err).Info("Failed to parse float for Duration field")
data.ConversionErrors = append(data.ConversionErrors, ConversionError{
Cause: fmt.Errorf("failed to parse float for Duration field: %v", err),
KeyV1: keysv1[configName],
ValueV1: configStrValue,
KeyV3: resourceToKey(res),
})
} else {
switch field.Tag.Get("configv1timescale") {
case "milliseconds":
fieldValue.Set(reflect.ValueOf(&metav1.Duration{Duration: time.Duration(duration * float64(time.Millisecond))}))
default:
fieldValue.Set(reflect.ValueOf(&metav1.Duration{Duration: time.Duration(duration * float64(time.Second))}))
}
setField = true
continue
}
}
// Set the field value based on the field type.
var kind reflect.Kind
if isPtr {
kind = field.Type.Elem().Kind()
} else {
kind = fieldValue.Kind()
}
switch kind {
case reflect.Uint32:
if value, err := strconv.ParseUint(configStrValue, 10, 32); err != nil {
logCxt.WithError(err).Info("Failed to parse uint32 field")
data.ConversionErrors = append(data.ConversionErrors, ConversionError{
Cause: fmt.Errorf("failed to parse uint32 field: %v", err),
KeyV1: keysv1[configName],
ValueV1: configStrValue,
KeyV3: resourceToKey(res),
})
continue
} else if isPtr {
vu := uint32(value)
fieldValue.Set(reflect.ValueOf(&vu))
} else {
fieldValue.SetUint(value)
}
case reflect.Int:
if value, err := strconv.ParseInt(configStrValue, 10, 64); err != nil {
logCxt.WithError(err).Info("Failed to parse int field")
data.ConversionErrors = append(data.ConversionErrors, ConversionError{
Cause: fmt.Errorf("failed to parse int field: %v", err),
KeyV1: keysv1[configName],
ValueV1: configStrValue,
KeyV3: resourceToKey(res),
})
continue
} else if isPtr {
vi := int(value)
fieldValue.Set(reflect.ValueOf(&vi))
} else {
fieldValue.SetInt(value)
}
case reflect.Bool:
if value, err := strconv.ParseBool(configStrValue); err != nil {
logCxt.WithError(err).Info("Failed to parse bool field")
data.ConversionErrors = append(data.ConversionErrors, ConversionError{
Cause: fmt.Errorf("failed to parse bool field: %v", err),
KeyV1: keysv1[configName],
ValueV1: configStrValue,
KeyV3: resourceToKey(res),
})
continue
} else if isPtr {
fieldValue.Set(reflect.ValueOf(&value))
} else {
fieldValue.SetBool(value)
}
case reflect.String:
if isPtr {
fieldValue.Set(reflect.ValueOf(&configStrValue))
} else {
fieldValue.SetString(configStrValue)
}
default:
logCxt.Info("Unhandle field type")
data.ConversionErrors = append(data.ConversionErrors, ConversionError{
Cause: fmt.Errorf("unhandled field type, please raise an issue on GitHub " +
"(https://github.com/dtest11/calico) that includes this error message"),
KeyV1: keysv1[configName],
ValueV1: configStrValue,
KeyV3: resourceToKey(res),
})
continue
}
// We must have set a field in the spec.
setField = true
}
if setField {
data.Resources = append(data.Resources, res)
}
return nil
}
func (m *migrationHelper) parseProtoPortFailed(msg string) error {
return fmt.Errorf("failed to parse ProtoPort-%s", msg)
}
func (m *migrationHelper) parseProtoPort(raw string) (*[]apiv3.ProtoPort, error) {
var result []apiv3.ProtoPort
for _, portStr := range strings.Split(raw, ",") {
portStr = strings.Trim(portStr, " ")
if portStr == "" {
continue
}
protocolStr := "tcp"
netStr := ""
// Check if IPv6 network is set
if strings.Contains(portStr, "[") && strings.Contains(portStr, "]") {
// Grab the IPv6 network
startIndex := strings.Index(portStr, "[")
endIndex := strings.Index(portStr, "]:")
netStr = portStr[startIndex+1 : endIndex]
// Remove the IPv6 network value from portStr
var withoutIPv6 strings.Builder
withoutIPv6.WriteString(portStr[:startIndex])
withoutIPv6.WriteString(portStr[endIndex+2:])
portStr = withoutIPv6.String()
}
parts := strings.Split(portStr, ":")
if len(parts) > 3 {
return nil, m.parseProtoPortFailed("ports should be <protocol>:<net>:<number> or <protocol>:<number> or <number>")
}
if len(parts) > 2 {
netStr = parts[1]
protocolStr = strings.ToUpper(parts[0])
portStr = parts[2]
}
if len(parts) == 2 {
protocolStr = strings.ToUpper(parts[0])
portStr = parts[1]
}
if protocolStr != "TCP" && protocolStr != "UDP" {
return nil, m.parseProtoPortFailed("unknown protocol: " + protocolStr)
}
port, err := strconv.Atoi(portStr)
if err != nil {
return nil, m.parseProtoPortFailed("ports should be integers")
}
if port < 0 || port > 65535 {
err = m.parseProtoPortFailed("ports must be in range 0-65535")
return nil, err
}
protoPort := apiv3.ProtoPort{
Protocol: protocolStr,
Port: uint16(port),
}
if netStr != "" {
_, netParsed, err := net.ParseCIDROrIP(netStr)
if err != nil {
err = m.parseProtoPortFailed("invalid CIDR or IP " + netStr)
return nil, err
}
protoPort.Net = netParsed.String()
}
result = append(result, protoPort)
}
return &result, nil
}
// Return the config name from the field. The field name is either specified in the
// configname tag, otherwise it just uses the struct field name.
func (m *migrationHelper) getConfigName(field reflect.StructField) string {
name := field.Tag.Get("confignamev1")
if name == "" {
name = field.Name
}
return name
}