/
deployments.go
514 lines (449 loc) · 17.3 KB
/
deployments.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
package stargate
import (
"fmt"
"strconv"
"strings"
"github.com/go-logr/logr"
"github.com/k8ssandra/k8ssandra-operator/pkg/annotations"
"github.com/k8ssandra/k8ssandra-operator/pkg/encryption"
"github.com/k8ssandra/k8ssandra-operator/pkg/images"
"github.com/k8ssandra/k8ssandra-operator/pkg/meta"
"github.com/k8ssandra/k8ssandra-operator/pkg/utils"
cassdcapi "github.com/k8ssandra/cass-operator/apis/cassandra/v1beta1"
coreapi "github.com/k8ssandra/k8ssandra-operator/apis/k8ssandra/v1alpha1"
api "github.com/k8ssandra/k8ssandra-operator/apis/stargate/v1alpha1"
"github.com/k8ssandra/k8ssandra-operator/pkg/cassandra"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)
const (
cassandraConfigDir = "/config"
cassandraConfigPath = "/config/cassandra.yaml"
cqlConfigPath = "/config/" + CqlConfigName
cassandraConfigMap = "cassandra-config"
)
const (
DefaultImageRepository = "stargateio"
DefaultImageName3 = "stargate-3_11"
DefaultImageName4 = "stargate-4_0"
DefaultImageNameDse68 = "stargate-dse-68"
DefaultVersion = "1.0.77"
// When changing the default version above, please also change the kubebuilder marker in
// apis/stargate/v1alpha1/stargate_types.go accordingly.
)
type ClusterVersion string
const (
ClusterVersion3 ClusterVersion = "3.11"
ClusterVersion4 ClusterVersion = "4.0"
ClusterVersion68 ClusterVersion = "6.8"
)
var (
defaultImage3 = images.Image{
Repository: DefaultImageRepository,
Name: DefaultImageName3,
Tag: "v" + DefaultVersion,
}
defaultImage4 = images.Image{
Repository: DefaultImageRepository,
Name: DefaultImageName4,
Tag: "v" + DefaultVersion,
}
defaultImage68 = images.Image{
Repository: DefaultImageRepository,
Name: DefaultImageNameDse68,
Tag: "v" + DefaultVersion,
}
)
// NewDeployments compute the Deployments to create for the given Stargate and CassandraDatacenter
// resources.
func NewDeployments(stargate *api.Stargate, dc *cassdcapi.CassandraDatacenter, logger logr.Logger) map[string]appsv1.Deployment {
clusterVersion := computeClusterVersion(dc)
seedService := computeSeedServiceUrl(dc)
racks := dc.GetRacks()
replicasByRack := cassdcapi.SplitRacks(int(stargate.Spec.Size), len(racks))
dnsPolicy := computeDNSPolicy(dc)
var deployments = make(map[string]appsv1.Deployment)
for i, rack := range racks {
replicas := int32(replicasByRack[i])
if replicas == 0 {
break
}
template := stargate.GetRackTemplate(rack.Name).MergeWith(&stargate.Spec.StargateDatacenterTemplate)
deploymentName := DeploymentName(dc, &rack)
image := computeImage(template, clusterVersion)
resources := computeResourceRequirements(template)
livenessProbe := computeLivenessProbe(template)
readinessProbe := computeReadinessProbe(template)
jvmOptions := computeJvmOptions(template)
volumes := computeVolumes(template, dc)
encryptionVolumes, encryptionVolumesMounts := computeEncryptionVolumes(stargate.Spec)
volumes = append(volumes, encryptionVolumes...)
volumeMounts := computeVolumeMounts(template, encryptionVolumesMounts)
serviceAccountName := computeServiceAccount(template)
nodeSelector := computeNodeSelector(template, dc)
tolerations := template.Tolerations
affinity := computeAffinity(template, dc, &rack)
podMeta := createPodMeta(stargate, deploymentName)
deployment := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: deploymentName,
Namespace: stargate.Namespace,
Annotations: map[string]string{},
Labels: createDeploymentLabels(stargate),
},
Spec: appsv1.DeploymentSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
api.StargateDeploymentLabel: deploymentName,
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: podMeta.Labels,
Annotations: podMeta.Annotations,
},
Spec: corev1.PodSpec{
ServiceAccountName: serviceAccountName,
HostNetwork: dc.IsHostNetworkEnabled(),
DNSPolicy: dnsPolicy,
ImagePullSecrets: images.CollectPullSecrets(image),
Containers: []corev1.Container{{
Name: deploymentName,
Image: image.String(),
ImagePullPolicy: image.PullPolicy,
Ports: []corev1.ContainerPort{
{ContainerPort: 8080, Name: "graphql"},
{ContainerPort: 8081, Name: "authorization"},
{ContainerPort: 8082, Name: "rest"},
{ContainerPort: 8084, Name: "health"},
{ContainerPort: 8085, Name: "metrics"},
{ContainerPort: 8090, Name: "grpc"},
{ContainerPort: 9042, Name: "native"},
{ContainerPort: 8609, Name: "inter-node-msg"},
{ContainerPort: 7000, Name: "intra-node"},
{ContainerPort: 7001, Name: "tls-intra-node"},
},
Resources: resources,
Env: []corev1.EnvVar{
{
Name: "LISTEN",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "status.podIP",
},
},
},
{Name: "JAVA_OPTS", Value: jvmOptions},
{Name: "CLUSTER_NAME", Value: dc.Spec.ClusterName},
{Name: "CLUSTER_VERSION", Value: string(clusterVersion)},
{Name: "SEED", Value: seedService},
{Name: "DATACENTER_NAME", Value: dc.DatacenterName()},
{Name: "RACK_NAME", Value: rack.Name},
// Watching bundles is unnecessary in a k8s deployment. See
// https://github.com/stargate/stargate/issues/1286 for
// details.
{Name: "DISABLE_BUNDLES_WATCH", Value: "true"},
},
LivenessProbe: &livenessProbe,
ReadinessProbe: &readinessProbe,
VolumeMounts: volumeMounts,
}},
NodeSelector: nodeSelector,
Tolerations: tolerations,
Affinity: affinity,
Volumes: volumes,
},
},
},
}
if coreapi.ServerDistribution(dc.Spec.ServerType) == coreapi.ServerDistributionDse {
// Stargate requires a DSE env variable set to "1" to use the right backend.
deployment.Spec.Template.Spec.Containers[0].Env = append(deployment.Spec.Template.Spec.Containers[0].Env, corev1.EnvVar{Name: "DSE", Value: "1"})
}
klusterName, nameFound := stargate.Labels[coreapi.K8ssandraClusterNameLabel]
klusterNamespace, namespaceFound := stargate.Labels[coreapi.K8ssandraClusterNamespaceLabel]
if nameFound && namespaceFound {
deployment.Labels[coreapi.K8ssandraClusterNameLabel] = klusterName
deployment.Spec.Template.Labels[coreapi.K8ssandraClusterNameLabel] = klusterName
deployment.Spec.Template.Labels[coreapi.K8ssandraClusterNamespaceLabel] = klusterNamespace
}
configureAuth(stargate, deployment)
configureVector(stargate, deployment, dc, logger)
annotations.AddHashAnnotation(deployment)
deployments[deploymentName] = *deployment
}
return deployments
}
func computeDNSPolicy(dc *cassdcapi.CassandraDatacenter) corev1.DNSPolicy {
if dc.IsHostNetworkEnabled() {
return corev1.DNSClusterFirstWithHostNet
}
return corev1.DNSClusterFirst
}
func computeSeedServiceUrl(dc *cassdcapi.CassandraDatacenter) string {
return cassdcapi.CleanupForKubernetes(dc.Spec.ClusterName) + "-seed-service." + dc.Namespace + ".svc"
}
func computeClusterVersion(dc *cassdcapi.CassandraDatacenter) ClusterVersion {
if coreapi.ServerDistribution(dc.Spec.ServerType) == coreapi.ServerDistributionDse {
return ClusterVersion68
}
cassandraVersion := dc.Spec.ServerVersion
if strings.HasPrefix(cassandraVersion, "3") {
return ClusterVersion3
} else {
return ClusterVersion4
}
}
func computeImage(template *api.StargateTemplate, clusterVersion ClusterVersion) *images.Image {
if clusterVersion == ClusterVersion68 {
return template.ContainerImage.ApplyDefaults(defaultImage68)
}
if clusterVersion == ClusterVersion3 {
return template.ContainerImage.ApplyDefaults(defaultImage3)
}
return template.ContainerImage.ApplyDefaults(defaultImage4)
}
func computeResourceRequirements(template *api.StargateTemplate) corev1.ResourceRequirements {
if template.Resources != nil {
return *template.Resources
} else {
heapSize := computeHeapSize(template)
memoryRequest := heapSize.DeepCopy()
memoryRequest.Add(memoryRequest) // heap x2
memoryLimit := memoryRequest.DeepCopy()
memoryLimit.Add(memoryLimit) // heap x4
return corev1.ResourceRequirements{
Requests: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceCPU: resource.MustParse("200m"),
corev1.ResourceMemory: memoryRequest,
},
Limits: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceCPU: resource.MustParse("1000m"),
corev1.ResourceMemory: memoryLimit,
},
}
}
}
func computeLivenessProbe(template *api.StargateTemplate) corev1.Probe {
var livenessProbe corev1.Probe
if template.LivenessProbe != nil {
livenessProbe = *template.LivenessProbe
} else {
livenessProbe = corev1.Probe{
TimeoutSeconds: 10,
InitialDelaySeconds: 30,
FailureThreshold: 5,
}
}
// The handlers cannot be user-specified, so force them now
livenessProbe.ProbeHandler = corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: "/checker/liveness",
Port: intstr.FromString("health"),
},
}
return livenessProbe
}
func computeReadinessProbe(template *api.StargateTemplate) corev1.Probe {
var readinessProbe corev1.Probe
if template.ReadinessProbe != nil {
readinessProbe = *template.ReadinessProbe
} else {
readinessProbe = corev1.Probe{
TimeoutSeconds: 10,
InitialDelaySeconds: 30,
FailureThreshold: 5,
}
}
// The handlers cannot be user-specified, so force them now
readinessProbe.ProbeHandler = corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: "/checker/readiness",
Port: intstr.FromString("health"),
},
}
return readinessProbe
}
func computeJvmOptions(template *api.StargateTemplate) string {
heapSize := computeHeapSize(template)
heapSizeInBytes := heapSize.Value()
jvmOptions := fmt.Sprintf("-XX:+CrashOnOutOfMemoryError -Xms%v -Xmx%v", heapSizeInBytes, heapSizeInBytes)
// The config map with the cassandra.yaml will always be created, even if it's empty.
// We then can always set the jvm option pointing to it.
jvmOptions += fmt.Sprintf(
" -Dstargate.unsafe.cassandra_config_path=%s",
cassandraConfigPath,
)
jvmOptions += fmt.Sprintf(
" -Dstargate.cql.config_path=%s",
cqlConfigPath,
)
return jvmOptions
}
func computeHeapSize(template *api.StargateTemplate) resource.Quantity {
if template.HeapSize != nil {
return *template.HeapSize
}
return resource.MustParse("256Mi")
}
// This config map will always be created by the k8ssandra controller.
// It will augment the user provided config map with encryption settings if enabled.
func computeVolumes(template *api.StargateTemplate, dc *cassdcapi.CassandraDatacenter) []corev1.Volume {
var volumes []corev1.Volume
volumes = append(volumes, corev1.Volume{
Name: "cassandra-config",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: GeneratedConfigMapName(dc.Spec.ClusterName, dc.DatacenterName()),
},
},
},
})
return volumes
}
func computeEncryptionVolumes(spec api.StargateSpec) ([]corev1.Volume, []corev1.VolumeMount) {
volumes := []corev1.Volume{}
mounts := []corev1.VolumeMount{}
if spec.CassandraEncryption != nil {
if spec.CassandraEncryption.ServerEncryptionStores != nil {
keystoreVolume, truststoreVolume := cassandra.EncryptionVolumes(encryption.StoreTypeServer, *spec.CassandraEncryption.ServerEncryptionStores)
volumes = append(volumes, *keystoreVolume)
mounts = append(mounts, encryptionStoreMount(*keystoreVolume, encryption.StoreTypeServer, encryption.StoreNameKeystore))
volumes = append(volumes, *truststoreVolume)
mounts = append(mounts, encryptionStoreMount(*truststoreVolume, encryption.StoreTypeServer, encryption.StoreNameTruststore))
}
if spec.CassandraEncryption.ClientEncryptionStores != nil {
keystoreVolume, truststoreVolume := cassandra.EncryptionVolumes(encryption.StoreTypeClient, *spec.CassandraEncryption.ClientEncryptionStores)
volumes = append(volumes, *keystoreVolume)
mounts = append(mounts, encryptionStoreMount(*keystoreVolume, encryption.StoreTypeClient, encryption.StoreNameKeystore))
volumes = append(volumes, *truststoreVolume)
mounts = append(mounts, encryptionStoreMount(*truststoreVolume, encryption.StoreTypeClient, encryption.StoreNameTruststore))
}
}
return volumes, mounts
}
func computeVolumeMounts(template *api.StargateTemplate, encryptionVolumesMounts []corev1.VolumeMount) []corev1.VolumeMount {
mounts := []corev1.VolumeMount{}
mounts = append(mounts, corev1.VolumeMount{
Name: "cassandra-config",
MountPath: cassandraConfigDir,
})
mounts = append(mounts, encryptionVolumesMounts...)
return mounts
}
func encryptionStoreMount(encryptionVolume corev1.Volume, storeType encryption.StoreType, storeName encryption.StoreName) corev1.VolumeMount {
return corev1.VolumeMount{
Name: encryptionVolume.Name,
MountPath: cassandra.StoreMountFullPath(storeType, storeName),
}
}
func computeServiceAccount(template *api.StargateTemplate) string {
if template.ServiceAccount != nil {
return *template.ServiceAccount
}
return "default"
}
func computeNodeSelector(template *api.StargateTemplate, dc *cassdcapi.CassandraDatacenter) map[string]string {
if template.NodeSelector != nil {
return template.NodeSelector
} else if dc.Spec.NodeSelector != nil {
return dc.Spec.NodeSelector
} else if dc.Spec.PodTemplateSpec != nil {
return dc.Spec.PodTemplateSpec.Spec.NodeSelector
}
return nil
}
func computeAffinity(template *api.StargateTemplate, dc *cassdcapi.CassandraDatacenter, rack *cassdcapi.Rack) *corev1.Affinity {
if template.Affinity != nil {
return template.Affinity
}
allowStargateOnDataNodes := false
if template != nil {
allowStargateOnDataNodes = template.AllowStargateOnDataNodes
}
return &corev1.Affinity{
NodeAffinity: computeNodeAffinity(dc, rack.Name),
PodAntiAffinity: computePodAntiAffinity(allowStargateOnDataNodes, dc, rack.Name),
}
}
func configureAuth(stargate *api.Stargate, deployment *appsv1.Deployment) {
if stargate.Spec.IsAuthEnabled() {
// Stargate reacts to the sole presence of this variable, regardless of its contents.
// Setting this env var triggers the --enable-auth flag in the Stargate container, which in
// turn triggers the setting of the -Dstargate.enable_auth=true system property.
// As a consequence:
// When this variable is absent, Stargate will use AllowAllAuthenticator.
// When this variable is present, Stargate will by default use PasswordAuthenticator, unless
// overridden by the stargate.authenticator_class_name system property (currently not
// exposed in the Stargate spec). Note that any other authenticator than
// PasswordAuthenticator will cause the REST APIs to be unusable, however the CQL API will
// still be usable.
// See https://github.com/stargate/stargate/issues/792 for more.
deployment.Spec.Template.Spec.Containers[0].Env = append(
deployment.Spec.Template.Spec.Containers[0].Env,
corev1.EnvVar{Name: "ENABLE_AUTH", Value: "true"},
)
authOptions := stargate.Spec.AuthOptions
if authOptions != nil {
switch authOptions.ApiAuthMethod {
case "Table", "":
for i, env := range deployment.Spec.Template.Spec.Containers[0].Env {
if env.Name == "JAVA_OPTS" {
env.Value += " -Dstargate.auth_id=AuthTableBasedService"
if authOptions.TokenTtlSeconds > 0 {
env.Value += " -Dstargate.auth_tokenttl="
env.Value += strconv.Itoa(authOptions.TokenTtlSeconds)
}
deployment.Spec.Template.Spec.Containers[0].Env[i] = env
break
}
}
case "JWT":
for i, env := range deployment.Spec.Template.Spec.Containers[0].Env {
if env.Name == "JAVA_OPTS" {
env.Value += " -Dstargate.auth_id=AuthJwtService"
env.Value += " -Dstargate.auth.jwt_provider_url="
env.Value += authOptions.JwtProviderUrl
deployment.Spec.Template.Spec.Containers[0].Env[i] = env
break
}
}
}
}
}
}
func createDeploymentLabels(stargate *api.Stargate) map[string]string {
commonLabels := map[string]string{
coreapi.NameLabel: coreapi.NameLabelValue,
coreapi.PartOfLabel: coreapi.PartOfLabelValue,
coreapi.ComponentLabel: coreapi.ComponentLabelValueStargate,
api.StargateLabel: stargate.Name,
}
if m := stargate.Spec.ResourceMeta; m != nil && m.CommonLabels != nil {
return utils.MergeMap(commonLabels, m.CommonLabels)
}
return commonLabels
}
func createPodMeta(stargate *api.Stargate, deploymentName string) meta.Tags {
labels := map[string]string{
coreapi.NameLabel: coreapi.NameLabelValue,
coreapi.PartOfLabel: coreapi.PartOfLabelValue,
coreapi.ComponentLabel: coreapi.ComponentLabelValueStargate,
api.StargateLabel: stargate.Name,
api.StargateDeploymentLabel: deploymentName,
}
var annotations map[string]string
if m := stargate.Spec.ResourceMeta; m != nil {
labels = utils.MergeMap(labels, m.CommonLabels, m.Pods.Labels)
annotations = m.Pods.Annotations
}
return meta.Tags{Labels: labels, Annotations: annotations}
}
func GeneratedConfigMapName(clusterName, dcName string) string {
return fmt.Sprintf("%s-%s-%s", cassdcapi.CleanupForKubernetes(clusterName), cassdcapi.CleanupForKubernetes(dcName), cassandraConfigMap)
}