-
Notifications
You must be signed in to change notification settings - Fork 156
/
template.go
372 lines (321 loc) · 12.1 KB
/
template.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
/*
Copyright 2020 The Kubermatic Kubernetes Platform contributors.
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 addon
import (
"bufio"
"bytes"
"fmt"
"os"
"path"
"strings"
"text/template"
semverlib "github.com/Masterminds/semver/v3"
"github.com/Masterminds/sprig/v3"
"go.uber.org/zap"
kubermaticv1 "k8c.io/api/v3/pkg/apis/kubermatic/v1"
kubermaticv1helper "k8c.io/api/v3/pkg/apis/kubermatic/v1/helper"
clusterhelper "k8c.io/kubermatic/v3/pkg/cluster"
"k8c.io/kubermatic/v3/pkg/resources"
"k8c.io/kubermatic/v3/pkg/resources/registry"
"k8c.io/kubermatic/v3/pkg/util/yaml"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
)
const (
ClusterTypeKubernetes = "kubernetes"
)
func txtFuncMap(overwriteRegistry string) template.FuncMap {
funcs := sprig.TxtFuncMap()
// Registry is deprecated and should not be used anymore.
funcs["Registry"] = registry.GetOverwriteFunc(overwriteRegistry)
funcs["Image"] = registry.GetImageRewriterFunc(overwriteRegistry)
funcs["join"] = strings.Join
return funcs
}
// This struct exists to keep BC compatibility between KKP 2.22 and 2.23,
// where Openstack => OpenStack and Kubevirt => KubeVirt were renamed.
type ClusterCredentials struct {
resources.Credentials
// Deprecated: Use OpenStack (capital S) instead.
Openstack resources.OpenStackCredentials
// Deprecated: Use KubeVirt (capital V) instead.
Kubevirt resources.KubeVirtCredentials
}
// TemplateData is the root context injected into each addon manifest file.
type TemplateData struct {
DatacenterName string
Cluster ClusterData
Credentials ClusterCredentials
Variables map[string]interface{}
}
func NewTemplateData(
cluster *kubermaticv1.Cluster,
credentials resources.Credentials,
kubeconfig string,
dnsClusterIP string,
dnsResolverIP string,
ipamAllocations *kubermaticv1.IPAMAllocationList,
variables map[string]interface{},
) (*TemplateData, error) {
providerName, err := kubermaticv1helper.ClusterCloudProviderName(cluster.Spec.Cloud)
if err != nil {
return nil, fmt.Errorf("failed to determine cloud provider name: %w", err)
}
if variables == nil {
variables = make(map[string]interface{})
}
if cluster.Spec.CNIPlugin == nil {
return nil, fmt.Errorf("cniPlugin must not be nil")
}
var csiOptions CSIOptions
if cluster.Spec.Cloud.VSphere != nil {
csiOptions.StoragePolicy = cluster.Spec.Cloud.VSphere.StoragePolicy
}
if cluster.Spec.Cloud.Nutanix != nil && cluster.Spec.Cloud.Nutanix.CSI != nil {
csiOptions.StorageContainer = cluster.Spec.Cloud.Nutanix.CSI.StorageContainer
csiOptions.Fstype = cluster.Spec.Cloud.Nutanix.CSI.Fstype
csiOptions.SsSegmentedIscsiNetwork = cluster.Spec.Cloud.Nutanix.CSI.SsSegmentedIscsiNetwork
}
if cluster.Spec.Cloud.VMwareCloudDirector != nil && cluster.Spec.Cloud.VMwareCloudDirector.CSI != nil {
csiOptions.Filesystem = cluster.Spec.Cloud.VMwareCloudDirector.CSI.Filesystem
csiOptions.StorageProfile = cluster.Spec.Cloud.VMwareCloudDirector.CSI.StorageProfile
}
csiMigration := metav1.HasAnnotation(cluster.ObjectMeta, kubermaticv1.CSIMigrationNeededAnnotation) || clusterhelper.CCMMigrationCompleted(cluster)
var ipvs kubermaticv1.IPVSConfiguration
if cluster.Spec.ClusterNetwork.IPVS != nil {
ipvs = *cluster.Spec.ClusterNetwork.IPVS
}
var kubeVirtStorageClasses []kubermaticv1.KubeVirtInfraStorageClass
if cluster.Spec.Cloud.KubeVirt != nil {
kubeVirtStorageClasses = cluster.Spec.Cloud.KubeVirt.StorageClasses
}
var ipamAllocationsData map[string]IPAMAllocation
if ipamAllocations != nil {
ipamAllocationsData = make(map[string]IPAMAllocation, len(ipamAllocations.Items))
for _, ipamAllocation := range ipamAllocations.Items {
ipamAllocationsData[ipamAllocation.Name] = IPAMAllocation{
Type: ipamAllocation.Spec.Type,
CIDR: ipamAllocation.Spec.CIDR,
Addresses: ipamAllocation.Spec.Addresses,
}
}
}
templateCredentials := ClusterCredentials{
Credentials: credentials,
}
templateCredentials.Openstack = templateCredentials.OpenStack
templateCredentials.Kubevirt = templateCredentials.KubeVirt
return &TemplateData{
DatacenterName: cluster.Spec.Cloud.DatacenterName,
Variables: variables,
Credentials: templateCredentials,
Cluster: ClusterData{
Type: ClusterTypeKubernetes,
Name: cluster.Name,
HumanReadableName: cluster.Spec.HumanReadableName,
Namespace: cluster.Status.NamespaceName,
Labels: cluster.Labels,
Annotations: cluster.Annotations,
Kubeconfig: kubeconfig,
//nolint:staticcheck
OwnerName: cluster.Status.UserName,
OwnerEmail: cluster.Status.UserEmail,
Address: cluster.Status.Address,
CloudProviderName: string(providerName),
Version: semverlib.MustParse(cluster.Status.Versions.ControlPlane.String()),
MajorMinorVersion: cluster.Status.Versions.ControlPlane.MajorMinor(),
Features: sets.KeySet(cluster.Spec.Features),
Network: ClusterNetwork{
DNSDomain: cluster.Spec.ClusterNetwork.DNSDomain,
DNSClusterIP: dnsClusterIP,
DNSResolverIP: dnsResolverIP,
PodCIDRBlocks: cluster.Spec.ClusterNetwork.Pods.CIDRBlocks,
ServiceCIDRBlocks: cluster.Spec.ClusterNetwork.Services.CIDRBlocks,
ProxyMode: cluster.Spec.ClusterNetwork.ProxyMode,
StrictArp: ipvs.StrictArp,
DualStack: cluster.Spec.ClusterNetwork.IsDualStack(),
PodCIDRIPv4: cluster.Spec.ClusterNetwork.Pods.GetIPv4CIDR(),
PodCIDRIPv6: cluster.Spec.ClusterNetwork.Pods.GetIPv6CIDR(),
NodeCIDRMaskSizeIPv4: resources.GetClusterNodeCIDRMaskSizeIPv4(cluster),
NodeCIDRMaskSizeIPv6: resources.GetClusterNodeCIDRMaskSizeIPv6(cluster),
IPAMAllocations: ipamAllocationsData,
NodePortRange: cluster.Spec.ComponentsOverride.Apiserver.NodePortRange,
},
CNIPlugin: CNIPlugin{
Type: cluster.Spec.CNIPlugin.Type.String(),
Version: cluster.Spec.CNIPlugin.Version,
},
CSI: csiOptions,
MLA: MLASettings{
MonitoringEnabled: cluster.Spec.MLA != nil && cluster.Spec.MLA.MonitoringEnabled,
LoggingEnabled: cluster.Spec.MLA != nil && cluster.Spec.MLA.LoggingEnabled,
},
CSIMigration: csiMigration,
KubeVirtInfraStorageClasses: kubeVirtStorageClasses,
},
}, nil
}
// ClusterData contains data related to the user cluster
// the addon is rendered for.
type ClusterData struct {
// Type is only "kubernetes"
Type string
// Name is the auto-generated, internal cluster name, e.g. "bbc8sc24wb".
Name string
// HumanReadableName is the user-specified cluster name.
HumanReadableName string
// Namespace is the full namespace for the cluster's control plane.
Namespace string
// OwnerName is the owner's full name.
OwnerName string
// OwnerEmail is the owner's e-mail address.
OwnerEmail string
// Labels are the labels users have configured for their cluster, including
// system-defined labels like the project ID.
Labels map[string]string
// Annotations are the annotations on the cluster resource, usually
// cloud-provider related information like regions.
Annotations map[string]string
// Kubeconfig is a YAML-encoded kubeconfig with cluster-admin permissions
// inside the user-cluster. The kubeconfig uses the external URL to reach
// the apiserver.
Kubeconfig string
// ClusterAddress stores access and address information of a cluster.
Address kubermaticv1.ClusterAddress
// CloudProviderName is the name of the cloud provider used, one of
// "alibaba", "aws", "azure", "bringyourown", "digitalocean", "gcp",
// "hetzner", "kubevirt", "openstack", "packet", "vsphere" depending on
// the configured datacenters.
CloudProviderName string
// Version is the exact current cluster version.
Version *semverlib.Version
// MajorMinorVersion is a shortcut for common testing on "Major.Minor" on the
// current cluster version.
MajorMinorVersion string
// Network contains DNS and CIDR settings for the cluster.
Network ClusterNetwork
// Features is a set of enabled features for this cluster.
Features sets.Set[string]
// CNIPlugin contains the CNIPlugin settings
CNIPlugin CNIPlugin
// CSI specific options, dependent on provider
CSI CSIOptions
// MLA contains monitoring, logging and alerting related settings for the user cluster.
MLA MLASettings
// CSIMigration indicates if the cluster needed the CSIMigration
CSIMigration bool
// KubeVirtInfraStorageClasses is a list of storage classes from KubeVirt infra cluster that are used for
// initialization of user cluster storage classes by the CSI driver kubevirt (hot pluggable disks)
KubeVirtInfraStorageClasses []kubermaticv1.KubeVirtInfraStorageClass
}
type ClusterNetwork struct {
DNSDomain string
DNSClusterIP string
DNSResolverIP string
PodCIDRBlocks []string
ServiceCIDRBlocks []string
ProxyMode string
StrictArp *bool
DualStack bool
PodCIDRIPv4 string
PodCIDRIPv6 string
NodeCIDRMaskSizeIPv4 int32
NodeCIDRMaskSizeIPv6 int32
IPAMAllocations map[string]IPAMAllocation
NodePortRange string
}
type IPAMAllocation struct {
Type kubermaticv1.IPAMPoolAllocationType
CIDR kubermaticv1.SubnetCIDR
Addresses []string
}
type CNIPlugin struct {
Type string
Version string
}
type MLASettings struct {
// MonitoringEnabled is the flag for enabling monitoring in user cluster.
MonitoringEnabled bool
// LoggingEnabled is the flag for enabling logging in user cluster.
LoggingEnabled bool
}
type CSIOptions struct {
// vsphere
// StoragePolicy is the storage policy to use for vsphere csi addon
StoragePolicy string
// nutanix
StorageContainer string
Fstype string
SsSegmentedIscsiNetwork *bool
// vmware Cloud Director
StorageProfile string
Filesystem string
}
type Manifest struct {
Content runtime.RawExtension
SourceFile string
}
func ParseFromFolder(log *zap.SugaredLogger, overwriteRegistry string, manifestPath string, data *TemplateData) ([]Manifest, error) {
var allManifests []Manifest
infos, err := os.ReadDir(manifestPath)
if err != nil {
return nil, err
}
for _, info := range infos {
filename := path.Join(manifestPath, info.Name())
infoLog := log.With("file", filename)
// recurse into subdirectory
if info.IsDir() {
subManifests, err := ParseFromFolder(log, overwriteRegistry, filename, data)
if err != nil {
return nil, err
}
allManifests = append(allManifests, subManifests...)
continue
}
if !strings.HasSuffix(filename, ".yaml") {
infoLog.Debug("Ignoring non-YAML file")
continue
}
infoLog.Debug("Processing file")
fbytes, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read file %s: %w", filename, err)
}
tpl, err := template.New(info.Name()).Funcs(txtFuncMap(overwriteRegistry)).Parse(string(fbytes))
if err != nil {
return nil, fmt.Errorf("failed to parse file %s: %w", filename, err)
}
bufferAll := bytes.NewBuffer([]byte{})
if err := tpl.Execute(bufferAll, data); err != nil {
return nil, fmt.Errorf("failed to execute templating on file %s: %w", filename, err)
}
sd := strings.TrimSpace(bufferAll.String())
if len(sd) == 0 {
infoLog.Debug("Skipping file as its empty after parsing")
continue
}
addonManifests, err := yaml.ParseMultipleDocuments(bufio.NewReader(bufferAll))
if err != nil {
return nil, fmt.Errorf("decoding failed for file %s: %w", filename, err)
}
for _, m := range addonManifests {
allManifests = append(allManifests, Manifest{
Content: m,
SourceFile: filename,
})
}
}
return allManifests, nil
}