-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathsolr_util.go
More file actions
1410 lines (1246 loc) · 48.3 KB
/
solr_util.go
File metadata and controls
1410 lines (1246 loc) · 48.3 KB
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 util
import (
"fmt"
solr "github.com/apache/solr-operator/api/v1beta1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
netv1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/utils/pointer"
"k8s.io/utils/ptr"
"sort"
"strconv"
"strings"
)
const (
SolrClientPortName = "solr-client"
SolrNodeContainer = "solrcloud-node"
DefaultSolrUser = 8983
DefaultSolrGroup = 8983
SolrStorageFinalizer = "storage.finalizers.solr.apache.org"
SolrZKConnectionStringAnnotation = "solr.apache.org/zkConnectionString"
SolrPVCTechnologyLabel = "solr.apache.org/technology"
SolrCloudPVCTechnology = "solr-cloud"
SolrPVCStorageLabel = "solr.apache.org/storage"
SolrCloudPVCDataStorage = "data"
SolrPVCInstanceLabel = "solr.apache.org/instance"
SolrXmlMd5Annotation = "solr.apache.org/solrXmlMd5"
SolrXmlFile = "solr.xml"
LogXmlMd5Annotation = "solr.apache.org/logXmlMd5"
LogXmlFile = "log4j2.xml"
// Protected StatefulSet annotations
// These are to be saved on a statefulSet update
ClusterOpsLockAnnotation = "solr.apache.org/clusterOpsLock"
ClusterOpsRetryQueueAnnotation = "solr.apache.org/clusterOpsRetryQueue"
StorageMinimumSizeAnnotation = "solr.apache.org/storageMinimumSize"
SolrIsNotStoppedReadinessCondition = "solr.apache.org/isNotStopped"
SolrReplicasNotEvictedReadinessCondition = "solr.apache.org/replicasNotEvicted"
DefaultStatefulSetPodManagementPolicy = appsv1.ParallelPodManagement
DistLibs = "/opt/solr/dist"
ContribLibs = "/opt/solr/contrib/%s/lib"
SysPropLibPlaceholder = "${solr.sharedLib:}"
)
var (
DefaultSolrVolumePrepInitContainerMemory = resource.NewScaledQuantity(50, 6)
DefaultSolrVolumePrepInitContainerCPU = resource.NewMilliQuantity(50, resource.DecimalExponent)
DefaultSolrZKPrepInitContainerMemory = resource.NewScaledQuantity(200, 6)
DefaultSolrZKPrepInitContainerCPU = resource.NewMilliQuantity(400, resource.DecimalExponent)
)
// GenerateStatefulSet returns a new appsv1.StatefulSet pointer generated for the SolrCloud instance
// object: SolrCloud instance
// replicas: the number of replicas for the SolrCloud instance
// storage: the size of the storage for the SolrCloud instance (e.g. 100Gi)
// zkConnectionString: the connectionString of the ZK instance to connect to
func GenerateStatefulSet(solrCloud *solr.SolrCloud, solrCloudStatus *solr.SolrCloudStatus, hostNameIPs map[string]string, reconcileConfigInfo map[string]string, tls *TLSCerts, security *SecurityConfig) *appsv1.StatefulSet {
terminationGracePeriod := int64(60)
solrPodPort := solrCloud.Spec.SolrAddressability.PodPort
defaultFSGroup := int64(DefaultSolrGroup)
probeScheme := corev1.URISchemeHTTP
if tls != nil {
probeScheme = corev1.URISchemeHTTPS
}
defaultProbeTimeout := int32(1)
defaultStartupProbe := createDefaultProbeHandlerForPath(probeScheme, solrPodPort, DefaultStartupProbePath)
defaultLivenessProbe := createDefaultProbeHandlerForPath(probeScheme, solrPodPort, DefaultLivenessProbePath)
defaultReadinessProbe := createDefaultProbeHandlerForPath(probeScheme, solrPodPort, DefaultReadinessProbePath)
labels := solrCloud.SharedLabelsWith(solrCloud.GetLabels())
selectorLabels := solrCloud.SharedLabels()
labels["technology"] = solr.SolrTechnologyLabel
selectorLabels["technology"] = solr.SolrTechnologyLabel
annotations := map[string]string{
SolrZKConnectionStringAnnotation: solrCloudStatus.ZkConnectionString(),
}
podLabels := labels
customSSOptions := solrCloud.Spec.CustomSolrKubeOptions.StatefulSetOptions
if nil != customSSOptions {
labels = MergeLabelsOrAnnotations(labels, customSSOptions.Labels)
annotations = MergeLabelsOrAnnotations(annotations, customSSOptions.Annotations)
}
customPodOptions := solrCloud.Spec.CustomSolrKubeOptions.PodOptions.DeepCopy()
var podAnnotations map[string]string
if nil != customPodOptions {
podLabels = MergeLabelsOrAnnotations(podLabels, customPodOptions.Labels)
podAnnotations = customPodOptions.Annotations
if customPodOptions.TerminationGracePeriodSeconds != nil {
terminationGracePeriod = *customPodOptions.TerminationGracePeriodSeconds
}
}
// The isNotStopped readiness gate will always be used for managedUpdates
podReadinessGates := []corev1.PodReadinessGate{
{
ConditionType: SolrIsNotStoppedReadinessCondition,
},
}
// Keep track of the SolrOpts that the Solr Operator needs to set
// These will be added to the SolrOpts given by the user.
allSolrOpts := []string{"-DhostPort=$(SOLR_NODE_PORT)"}
// Volumes & Mounts
solrVolumes := []corev1.Volume{
{
Name: "solr-xml",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: reconcileConfigInfo[SolrXmlFile],
},
Items: []corev1.KeyToPath{
{
Key: SolrXmlFile,
Path: SolrXmlFile,
},
},
DefaultMode: &PublicReadOnlyPermissions,
},
},
},
{
Name: "tmp",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
},
}
solrDataVolumeName := solrCloud.DataVolumeName()
var pvcs []corev1.PersistentVolumeClaim
if solrCloud.UsesPersistentStorage() {
pvc := solrCloud.Spec.StorageOptions.PersistentStorage.PersistentVolumeClaimTemplate.DeepCopy()
// Set the default name of the pvc
pvc.ObjectMeta.Name = solrDataVolumeName
// Set some defaults in the PVC Spec
if len(pvc.Spec.AccessModes) == 0 {
pvc.Spec.AccessModes = []corev1.PersistentVolumeAccessMode{
corev1.ReadWriteOnce,
}
}
if pvc.Spec.VolumeMode == nil {
temp := corev1.PersistentVolumeFilesystem
pvc.Spec.VolumeMode = &temp
}
// Add internally-used labels.
internalLabels := map[string]string{
SolrPVCTechnologyLabel: SolrCloudPVCTechnology,
SolrPVCStorageLabel: SolrCloudPVCDataStorage,
SolrPVCInstanceLabel: solrCloud.Name,
}
pvc.ObjectMeta.Labels = MergeLabelsOrAnnotations(internalLabels, pvc.ObjectMeta.Labels)
pvcs = []corev1.PersistentVolumeClaim{
{
ObjectMeta: metav1.ObjectMeta{
Name: pvc.ObjectMeta.Name,
Labels: pvc.ObjectMeta.Labels,
Annotations: pvc.ObjectMeta.Annotations,
},
Spec: pvc.Spec,
},
}
if pvc.Spec.Resources.Requests.Storage() != nil {
annotations[StorageMinimumSizeAnnotation] = pvc.Spec.Resources.Requests.Storage().String()
if podAnnotations == nil {
podAnnotations = make(map[string]string, 1)
}
podAnnotations[StorageMinimumSizeAnnotation] = pvc.Spec.Resources.Requests.Storage().String()
}
} else {
ephemeralVolume := corev1.Volume{
Name: solrDataVolumeName,
VolumeSource: corev1.VolumeSource{},
}
if solrCloud.Spec.StorageOptions.EphemeralStorage != nil {
if nil != solrCloud.Spec.StorageOptions.EphemeralStorage.HostPath {
ephemeralVolume.VolumeSource.HostPath = solrCloud.Spec.StorageOptions.EphemeralStorage.HostPath
} else if nil != solrCloud.Spec.StorageOptions.EphemeralStorage.EmptyDir {
ephemeralVolume.VolumeSource.EmptyDir = solrCloud.Spec.StorageOptions.EphemeralStorage.EmptyDir
} else {
ephemeralVolume.VolumeSource.EmptyDir = &corev1.EmptyDirVolumeSource{}
}
} else {
ephemeralVolume.VolumeSource.EmptyDir = &corev1.EmptyDirVolumeSource{}
}
solrVolumes = append(solrVolumes, ephemeralVolume)
// Add an evictPodReadinessCondition for when deleting pods with ephemeral storage
podReadinessGates = append(podReadinessGates, corev1.PodReadinessGate{
ConditionType: SolrReplicasNotEvictedReadinessCondition,
})
}
volumeMounts := []corev1.VolumeMount{{Name: solrDataVolumeName, MountPath: "/var/solr/data"}}
// Add necessary specs for backupRepos
backupEnvVars := make([]corev1.EnvVar, 0)
for _, repo := range solrCloud.Spec.BackupRepositories {
volumeSource, mount := RepoVolumeSourceAndMount(&repo, solrCloud.Name)
if volumeSource != nil {
solrVolumes = append(solrVolumes, corev1.Volume{
Name: RepoVolumeName(&repo),
VolumeSource: *volumeSource,
})
volumeMounts = append(volumeMounts, *mount)
}
repoEnvVars := RepoEnvVars(&repo)
if len(repoEnvVars) > 0 {
backupEnvVars = append(backupEnvVars, repoEnvVars...)
}
}
// Add annotation specifying the backupRepositories available with this version of the Pod.
podAnnotations = SetAvailableBackupRepos(solrCloud, podAnnotations)
if nil != customPodOptions {
// Add Custom Volumes to pod
for _, volume := range customPodOptions.Volumes {
// Only add the container mount if one has been provided.
if volume.DefaultContainerMount != nil {
volume.DefaultContainerMount.Name = volume.Name
volumeMounts = append(volumeMounts, *volume.DefaultContainerMount)
}
solrVolumes = append(solrVolumes, corev1.Volume{
Name: volume.Name,
VolumeSource: volume.Source,
})
}
}
// Host Aliases
hostAliases := make([]corev1.HostAlias, len(hostNameIPs))
if len(hostAliases) == 0 {
hostAliases = nil
} else {
hostNames := make([]string, len(hostNameIPs))
index := 0
for hostName := range hostNameIPs {
hostNames[index] = hostName
index += 1
}
sort.Strings(hostNames)
for index, hostName := range hostNames {
hostAliases[index] = corev1.HostAlias{
IP: hostNameIPs[hostName],
Hostnames: []string{hostName},
}
index++
}
}
solrHostName := solrCloud.AdvertisedNodeHost("$(POD_NAME)")
solrAdressingPort := solrCloud.NodePort()
// Solr can take longer than SOLR_STOP_WAIT to run solr stop, give it a few extra seconds before forcefully killing the pod.
solrStopWait := terminationGracePeriod - 5
if solrStopWait < 0 {
solrStopWait = 0
}
// Environment Variables
envVars := []corev1.EnvVar{
{
Name: "SOLR_JAVA_MEM",
Value: solrCloud.Spec.SolrJavaMem,
},
{
Name: "SOLR_HOME",
Value: "/var/solr/data",
},
{
// This is the port that jetty will listen on
Name: "SOLR_PORT",
Value: strconv.Itoa(solrPodPort),
},
{
// This is the port that the Solr Node will advertise itself as listening on in live_nodes
// TODO Remove in 0.9.0 once users have had a chance to switch any custom solr.xml files over to using the `solr.port.advertise` placeholder
Name: "SOLR_NODE_PORT",
Value: strconv.Itoa(solrAdressingPort),
},
{
// Supercedes SOLR_NODE_PORT above. 'bin/solr' converts to 'solr.port.advertise' sysprop automatically.
Name: "SOLR_PORT_ADVERTISE",
Value: strconv.Itoa(solrAdressingPort),
},
// POD_HOSTNAME is deprecated and will be removed in a future version. Use POD_NAME instead
{
Name: "POD_HOSTNAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "metadata.name",
APIVersion: "v1",
},
},
},
{
Name: "POD_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "metadata.name",
APIVersion: "v1",
},
},
},
{
Name: "POD_IP",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "status.podIP",
APIVersion: "v1",
},
},
},
{
Name: "POD_NAMESPACE",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "metadata.namespace",
APIVersion: "v1",
},
},
},
{
Name: "SOLR_HOST",
Value: solrHostName,
},
{
Name: "SOLR_LOG_LEVEL",
Value: solrCloud.Spec.SolrLogLevel,
},
{
Name: "GC_TUNE",
Value: solrCloud.Spec.SolrGCTune,
},
{
Name: "SOLR_STOP_WAIT",
Value: strconv.FormatInt(solrStopWait, 10),
},
}
// Add all necessary information for connection to Zookeeper
zkEnvVars, zkSolrOpt, hasChroot := createZkConnectionEnvVars(solrCloud, solrCloudStatus)
if zkSolrOpt != "" {
allSolrOpts = append(allSolrOpts, zkSolrOpt)
}
envVars = append(envVars, zkEnvVars...)
// Add envVars for backupRepos if any are needed
if len(backupEnvVars) > 0 {
envVars = append(envVars, backupEnvVars...)
}
// Only have a postStart command to create the chRoot, if it is not '/' (which does not need to be created)
var postStart *corev1.LifecycleHandler
if hasChroot {
postStart = &corev1.LifecycleHandler{
Exec: &corev1.ExecAction{
Command: []string{"sh", "-c", "solr zk ls ${ZK_CHROOT} -z ${ZK_SERVER} || solr zk mkroot ${ZK_CHROOT} -z ${ZK_SERVER}"},
},
}
}
// Default preStop hook
preStop := &corev1.LifecycleHandler{
Exec: &corev1.ExecAction{
Command: []string{"solr", "stop", "-p", strconv.Itoa(solrPodPort)},
},
}
// Add Custom EnvironmentVariables to the solr container
if nil != customPodOptions {
envVars = append(envVars, customPodOptions.EnvVariables...)
}
// Did the user provide a custom log config?
if reconcileConfigInfo[LogXmlFile] != "" {
if reconcileConfigInfo[LogXmlMd5Annotation] != "" {
if podAnnotations == nil {
podAnnotations = make(map[string]string, 1)
}
podAnnotations[LogXmlMd5Annotation] = reconcileConfigInfo[LogXmlMd5Annotation]
}
// cannot use /var/solr as a mountPath, so mount the custom log config
// in a sub-dir named after the user-provided ConfigMap
volMount, envVar, newVolume := setupVolumeMountForUserProvidedConfigMapEntry(reconcileConfigInfo, LogXmlFile, solrVolumes, "LOG4J_PROPS")
volumeMounts = append(volumeMounts, *volMount)
envVars = append(envVars, *envVar)
if newVolume != nil {
solrVolumes = append(solrVolumes, *newVolume)
}
}
// track the MD5 of the custom solr.xml in the pod spec annotations,
// so we get a rolling restart when the configMap changes
if reconcileConfigInfo[SolrXmlMd5Annotation] != "" {
if podAnnotations == nil {
podAnnotations = make(map[string]string, 1)
}
podAnnotations[SolrXmlMd5Annotation] = reconcileConfigInfo[SolrXmlMd5Annotation]
}
if solrCloud.Spec.SolrOpts != "" {
allSolrOpts = append(allSolrOpts, solrCloud.Spec.SolrOpts)
}
// Add SOLR_OPTS last, so that it can use values from all of the other ENV_VARS
envVars = append(envVars, corev1.EnvVar{
Name: "SOLR_OPTS",
Value: strings.Join(allSolrOpts, " "),
})
initContainers := generateSolrSetupInitContainers(solrCloud, solrCloudStatus, solrDataVolumeName, security)
// Add user defined additional init containers
if customPodOptions != nil && len(customPodOptions.InitContainers) > 0 {
initContainers = append(initContainers, customPodOptions.InitContainers...)
}
containers := []corev1.Container{
{
Name: SolrNodeContainer,
Image: solrCloud.Spec.SolrImage.ToImageName(),
ImagePullPolicy: solrCloud.Spec.SolrImage.PullPolicy,
Ports: []corev1.ContainerPort{
{
ContainerPort: int32(solrPodPort),
Name: SolrClientPortName,
Protocol: "TCP",
},
},
// Wait 60 seconds for Solr to startup
StartupProbe: &corev1.Probe{
InitialDelaySeconds: 10,
TimeoutSeconds: defaultProbeTimeout,
SuccessThreshold: 1,
FailureThreshold: 10,
PeriodSeconds: 5,
ProbeHandler: defaultStartupProbe,
},
// Kill Solr if it is unavailable for any 60-second period
LivenessProbe: &corev1.Probe{
TimeoutSeconds: defaultProbeTimeout,
SuccessThreshold: 1,
FailureThreshold: 3,
PeriodSeconds: 20,
ProbeHandler: defaultLivenessProbe,
},
// Do not route requests to solr if it is not available for any 20-second period
ReadinessProbe: &corev1.Probe{
TimeoutSeconds: defaultProbeTimeout,
SuccessThreshold: 1,
FailureThreshold: 2,
PeriodSeconds: 10,
ProbeHandler: defaultReadinessProbe,
},
VolumeMounts: volumeMounts,
Env: envVars,
Lifecycle: &corev1.Lifecycle{
PostStart: postStart,
PreStop: preStop,
},
},
}
// Add user defined additional sidecar containers
if customPodOptions != nil && len(customPodOptions.SidecarContainers) > 0 {
containers = append(containers, customPodOptions.SidecarContainers...)
}
// Decide which update strategy to use
updateStrategy := appsv1.OnDeleteStatefulSetStrategyType
if solrCloud.Spec.UpdateStrategy.Method == solr.StatefulSetUpdate {
// Only use the rolling update strategy if the StatefulSetUpdate method is specified.
updateStrategy = appsv1.RollingUpdateStatefulSetStrategyType
}
// Determine which podManagementPolicy to use for the statefulSet
podManagementPolicy := DefaultStatefulSetPodManagementPolicy
if solrCloud.Spec.CustomSolrKubeOptions.StatefulSetOptions != nil && solrCloud.Spec.CustomSolrKubeOptions.StatefulSetOptions.PodManagementPolicy != "" {
podManagementPolicy = solrCloud.Spec.CustomSolrKubeOptions.StatefulSetOptions.PodManagementPolicy
}
// Create the Stateful Set
stateful := &appsv1.StatefulSet{
ObjectMeta: metav1.ObjectMeta{
Name: solrCloud.StatefulSetName(),
Namespace: solrCloud.GetNamespace(),
Labels: labels,
Annotations: annotations,
},
Spec: appsv1.StatefulSetSpec{
Selector: &metav1.LabelSelector{
MatchLabels: selectorLabels,
},
ServiceName: solrCloud.HeadlessServiceName(),
Replicas: solrCloud.Spec.Replicas,
PodManagementPolicy: podManagementPolicy,
UpdateStrategy: appsv1.StatefulSetUpdateStrategy{
Type: updateStrategy,
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: podLabels,
Annotations: podAnnotations,
},
Spec: corev1.PodSpec{
TerminationGracePeriodSeconds: &terminationGracePeriod,
SecurityContext: &corev1.PodSecurityContext{
FSGroup: &defaultFSGroup,
},
Volumes: solrVolumes,
InitContainers: initContainers,
HostAliases: hostAliases,
Containers: containers,
ReadinessGates: podReadinessGates,
},
},
VolumeClaimTemplates: pvcs,
},
}
if solrCloud.UsesHeadlessService() {
stateful.Spec.Template.Spec.Subdomain = solrCloud.HeadlessServiceName()
}
var imagePullSecrets []corev1.LocalObjectReference
if customPodOptions != nil {
imagePullSecrets = customPodOptions.ImagePullSecrets
}
if solrCloud.Spec.SolrImage.ImagePullSecret != "" {
imagePullSecrets = append(
imagePullSecrets,
corev1.LocalObjectReference{Name: solrCloud.Spec.SolrImage.ImagePullSecret},
)
}
stateful.Spec.Template.Spec.ImagePullSecrets = imagePullSecrets
if nil != customPodOptions {
solrContainer := &stateful.Spec.Template.Spec.Containers[0]
if customPodOptions.ServiceAccountName != "" {
stateful.Spec.Template.Spec.ServiceAccountName = customPodOptions.ServiceAccountName
}
if customPodOptions.Affinity != nil {
stateful.Spec.Template.Spec.Affinity = customPodOptions.Affinity
}
if customPodOptions.Resources.Limits != nil || customPodOptions.Resources.Requests != nil {
solrContainer.Resources = customPodOptions.Resources
}
if customPodOptions.PodSecurityContext != nil {
stateful.Spec.Template.Spec.SecurityContext = customPodOptions.PodSecurityContext
if stateful.Spec.Template.Spec.SecurityContext.FSGroup == nil {
stateful.Spec.Template.Spec.SecurityContext.FSGroup = &defaultFSGroup
}
}
if customPodOptions.Lifecycle != nil {
solrContainer.Lifecycle = customPodOptions.Lifecycle
}
if customPodOptions.Tolerations != nil {
stateful.Spec.Template.Spec.Tolerations = customPodOptions.Tolerations
}
if customPodOptions.NodeSelector != nil {
stateful.Spec.Template.Spec.NodeSelector = customPodOptions.NodeSelector
}
if customPodOptions.StartupProbe != nil {
// Default Solr container does not contain a startupProbe, so copy the livenessProbe
baseProbe := solrContainer.LivenessProbe.DeepCopy()
// Two options are different by default from the livenessProbe
baseProbe.TimeoutSeconds = 30
baseProbe.FailureThreshold = 15
solrContainer.StartupProbe = customizeProbe(baseProbe, *customPodOptions.StartupProbe)
}
if customPodOptions.LivenessProbe != nil {
solrContainer.LivenessProbe = customizeProbe(solrContainer.LivenessProbe, *customPodOptions.LivenessProbe)
}
if customPodOptions.ReadinessProbe != nil {
solrContainer.ReadinessProbe = customizeProbe(solrContainer.ReadinessProbe, *customPodOptions.ReadinessProbe)
}
if customPodOptions.PriorityClassName != "" {
stateful.Spec.Template.Spec.PriorityClassName = customPodOptions.PriorityClassName
}
if len(customPodOptions.TopologySpreadConstraints) > 0 {
stateful.Spec.Template.Spec.TopologySpreadConstraints = customPodOptions.TopologySpreadConstraints
// Set the label selector for constraints to the statefulSet label selector, if none is provided
for i := range stateful.Spec.Template.Spec.TopologySpreadConstraints {
if stateful.Spec.Template.Spec.TopologySpreadConstraints[i].LabelSelector == nil {
stateful.Spec.Template.Spec.TopologySpreadConstraints[i].LabelSelector = stateful.Spec.Selector.DeepCopy()
}
}
}
}
// Enrich the StatefulSet config to enable TLS on Solr pods if needed
if tls != nil {
tls.enableTLSOnSolrCloudStatefulSet(stateful)
}
// If probes require auth is set OR tls is configured to want / need client auth, then reconfigure the probes to use an exec
if (solrCloud.Spec.SolrSecurity != nil && solrCloud.Spec.SolrSecurity.ProbesRequireAuth) || (tls != nil && tls.ServerConfig != nil && tls.ServerConfig.Options.ClientAuth != solr.None) {
enableSecureProbesOnSolrCloudStatefulSet(solrCloud, stateful)
} else {
// If we are not using secure probes, but still using TLS, then make sure that the HOST header is correct when sending liveness and readiness checks.
// Otherwise it is likely that the SNI checks will fail for newer versions of Solr (9.2+)
setHostHeaderForProbesOnSolrCloudStatefulSet(solrCloud, stateful)
}
return stateful
}
// MaintainPreservedStatefulSetFields makes sure that certain fields in the SolrCloud statefulSet are preserved
// across updates to the statefulSet. The code that generates an "idempotent" statefulSet might not have the information
// that was used when these values were populated, so they must be saved when the new "expected" statefulSet overwrites
// all the information on the new "found" statefulSet.
func MaintainPreservedStatefulSetFields(expected, found *appsv1.StatefulSet) {
// Cluster Operations are saved in the annotations of the SolrCloud StatefulSet.
// ClusterOps information is saved to the statefulSet independently of the general StatefulSet update.
// These annotations can also not be overridden set by the user.
if found.Annotations != nil {
if lock, hasLock := found.Annotations[ClusterOpsLockAnnotation]; hasLock {
if expected.Annotations == nil {
expected.Annotations = make(map[string]string, 1)
}
expected.Annotations[ClusterOpsLockAnnotation] = lock
}
if queue, hasQueue := found.Annotations[ClusterOpsRetryQueueAnnotation]; hasQueue {
if expected.Annotations == nil {
expected.Annotations = make(map[string]string, 1)
}
expected.Annotations[ClusterOpsRetryQueueAnnotation] = queue
}
if storage, hasStorage := found.Annotations[StorageMinimumSizeAnnotation]; hasStorage {
if expected.Annotations == nil {
expected.Annotations = make(map[string]string, 1)
}
expected.Annotations[StorageMinimumSizeAnnotation] = storage
}
}
if found.Spec.Template.Annotations != nil {
// Note: the Pod template storage annotation is used to start a rolling restart,
// it should always match the StatefulSet's storage annotation
if storage, hasStorage := found.Spec.Template.Annotations[StorageMinimumSizeAnnotation]; hasStorage {
if expected.Spec.Template.Annotations == nil {
expected.Spec.Template.Annotations = make(map[string]string, 1)
}
expected.Spec.Template.Annotations[StorageMinimumSizeAnnotation] = storage
}
}
// Scaling (i.e. changing) the number of replicas in the SolrCloud statefulSet is handled during the clusterOps
// section of the SolrCloud reconcile loop
expected.Spec.Replicas = found.Spec.Replicas
}
func generateSolrSetupInitContainers(solrCloud *solr.SolrCloud, solrCloudStatus *solr.SolrCloudStatus, solrDataVolumeName string, security *SecurityConfig) (containers []corev1.Container) {
// The setup of the solr.xml will always be necessary
volumeMounts := []corev1.VolumeMount{
{
Name: "solr-xml",
MountPath: "/tmp",
},
{
Name: solrDataVolumeName,
MountPath: "/tmp-config",
},
}
setupCommands := []string{"cp /tmp/solr.xml /tmp-config/solr.xml"}
// Figure out the solrUser and solrGroup to use
solrUser := DefaultSolrUser
solrFSGroup := DefaultSolrGroup
// Only add a user to the initContainer if one isn't provided in the podSecurityContext
// This is so that we can check if the backupDir is writable given the default user (since no user is provided)
addUserToInitContainer := true
if solrCloud.Spec.CustomSolrKubeOptions.PodOptions != nil {
solrPodSecurityContext := solrCloud.Spec.CustomSolrKubeOptions.PodOptions.PodSecurityContext
if solrPodSecurityContext != nil {
if solrPodSecurityContext.RunAsUser != nil {
solrUser = int(*solrPodSecurityContext.RunAsUser)
addUserToInitContainer = false
} else if solrPodSecurityContext.RunAsNonRoot != nil && *solrPodSecurityContext.RunAsNonRoot {
// we can't add users to the initContainer, even if we want to, since we cannot run as root.
addUserToInitContainer = false
}
if solrPodSecurityContext.FSGroup != nil {
solrFSGroup = int(*solrPodSecurityContext.FSGroup)
}
}
}
// Add prep for backup-restore Repositories
// This entails setting the correct permissions for the directory
solrUserAdded := false
for _, repo := range solrCloud.Spec.BackupRepositories {
if IsRepoVolume(&repo) {
if _, volumeMount := RepoVolumeSourceAndMount(&repo, solrCloud.Name); volumeMount != nil {
volumeMounts = append(volumeMounts, *volumeMount)
if addUserToInitContainer && !solrUserAdded {
setupCommands = append(setupCommands, fmt.Sprintf("addgroup -g %d solr", solrFSGroup))
setupCommands = append(setupCommands, fmt.Sprintf("adduser -u %d -G solr -H -D solr", DefaultSolrUser))
// Only add users once even if there are many backup repos
solrUserAdded = true
}
testDirCommand := "test -w " + volumeMount.MountPath
if addUserToInitContainer {
testDirCommand = fmt.Sprintf("su solr -c '%s'", testDirCommand)
}
setupCommands = append(setupCommands, fmt.Sprintf(
"(%s || chown -R %d:%d %s)",
testDirCommand,
solrUser,
solrFSGroup,
volumeMount.MountPath))
}
}
}
volumePrepResources := corev1.ResourceList{
corev1.ResourceCPU: *DefaultSolrVolumePrepInitContainerCPU,
corev1.ResourceMemory: *DefaultSolrVolumePrepInitContainerMemory,
}
volumePrepInitContainer := corev1.Container{
Name: "cp-solr-xml",
Image: solrCloud.Spec.BusyBoxImage.ToImageName(),
ImagePullPolicy: solrCloud.Spec.BusyBoxImage.PullPolicy,
Command: []string{"sh", "-c", strings.Join(setupCommands, " && ")},
VolumeMounts: volumeMounts,
Resources: corev1.ResourceRequirements{
Requests: volumePrepResources,
Limits: volumePrepResources,
},
}
containers = append(containers, volumePrepInitContainer)
if hasZKSetupContainer, zkSetupContainer := generateZKInteractionInitContainer(solrCloud, solrCloudStatus, security); hasZKSetupContainer {
containers = append(containers, zkSetupContainer)
}
// If the user has provided custom resources for the default init containers, use them
customPodOptions := solrCloud.Spec.CustomSolrKubeOptions.PodOptions
if nil != customPodOptions {
resources := customPodOptions.DefaultInitContainerResources
if resources.Limits != nil || resources.Requests != nil {
for i := range containers {
containers[i].Resources = resources
}
}
}
return containers
}
func createDefaultProbeHandlerForPath(probeScheme corev1.URIScheme, solrPodPort int, path string) corev1.ProbeHandler {
return corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Scheme: probeScheme,
Path: "/solr" + path,
Port: intstr.FromInt(solrPodPort),
},
}
}
const DefaultSolrXML = `<?xml version="1.0" encoding="UTF-8" ?>
<solr>
%s
<solrcloud>
<str name="host">${host:}</str>
<int name="hostPort">${solr.port.advertise:80}</int>
<str name="hostContext">${hostContext:solr}</str>
<bool name="genericCoreNodeNames">${genericCoreNodeNames:true}</bool>
<int name="zkClientTimeout">${zkClientTimeout:30000}</int>
<int name="distribUpdateSoTimeout">${distribUpdateSoTimeout:600000}</int>
<int name="distribUpdateConnTimeout">${distribUpdateConnTimeout:60000}</int>
<str name="zkCredentialsProvider">${zkCredentialsProvider:org.apache.solr.common.cloud.DefaultZkCredentialsProvider}</str>
<str name="zkACLProvider">${zkACLProvider:org.apache.solr.common.cloud.DefaultZkACLProvider}</str>
</solrcloud>
<shardHandlerFactory name="shardHandlerFactory"
class="HttpShardHandlerFactory">
<int name="socketTimeout">${socketTimeout:600000}</int>
<int name="connTimeout">${connTimeout:60000}</int>
</shardHandlerFactory>
<int name="maxBooleanClauses">${solr.max.booleanClauses:1024}</int>
<str name="allowPaths">${solr.allowPaths:}</str>
<metrics enabled="${metricsEnabled:true}"/>
%s
</solr>
`
// GenerateConfigMap returns a new corev1.ConfigMap pointer generated for the SolrCloud instance solr.xml
// solrCloud: SolrCloud instance
func GenerateConfigMap(solrCloud *solr.SolrCloud) *corev1.ConfigMap {
labels := solrCloud.SharedLabelsWith(solrCloud.GetLabels())
var annotations map[string]string
customOptions := solrCloud.Spec.CustomSolrKubeOptions.ConfigMapOptions
if nil != customOptions {
labels = MergeLabelsOrAnnotations(labels, customOptions.Labels)
annotations = MergeLabelsOrAnnotations(annotations, customOptions.Annotations)
}
configMap := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: solrCloud.ConfigMapName(),
Namespace: solrCloud.GetNamespace(),
Labels: labels,
Annotations: annotations,
},
Data: map[string]string{
"solr.xml": GenerateSolrXMLStringForCloud(solrCloud),
},
}
return configMap
}
func GenerateSolrXMLStringForCloud(solrCloud *solr.SolrCloud) string {
backupSection, solrModules, additionalLibs := GenerateBackupRepositoriesForSolrXml(solrCloud.Spec.BackupRepositories)
solrModules = append(solrModules, solrCloud.Spec.SolrModules...)
additionalLibs = append(additionalLibs, solrCloud.Spec.AdditionalLibs...)
return GenerateSolrXMLString(backupSection, solrModules, additionalLibs)
}
func GenerateSolrXMLString(backupSection string, solrModules []string, additionalLibs []string) string {
return fmt.Sprintf(DefaultSolrXML, GenerateAdditionalLibXMLPart(solrModules, additionalLibs), backupSection)
}
func GenerateAdditionalLibXMLPart(solrModules []string, additionalLibs []string) string {
libs := make(map[string]bool, 0)
// Placeholder for users to specify libs via sysprop
libs[SysPropLibPlaceholder] = true
// Add all module library locations
if len(solrModules) > 0 {
libs[DistLibs] = true
}
for _, module := range solrModules {
libs[fmt.Sprintf(ContribLibs, module)] = true
}
// Add all custom library locations
for _, libPath := range additionalLibs {
libs[libPath] = true
}
libList := make([]string, 0)
for lib := range libs {
libList = append(libList, lib)
}
sort.Strings(libList)
return fmt.Sprintf("<str name=\"sharedLib\">%s</str>", strings.Join(libList, ","))
}
func getAppProtocol(solrCloud *solr.SolrCloud) *string {
// Only use https, because for non-tls we need to support both http & http2 for Solr
if solrCloud.Spec.SolrTLS != nil {
return pointer.String("https")
} else {
return nil
}
}
// GenerateCommonService returns a new corev1.Service pointer generated for the entire SolrCloud instance
// solrCloud: SolrCloud instance
func GenerateCommonService(solrCloud *solr.SolrCloud) *corev1.Service {
labels := solrCloud.SharedLabelsWith(solrCloud.GetLabels())
labels["service-type"] = "common"
selectorLabels := solrCloud.SharedLabels()
selectorLabels["technology"] = solr.SolrTechnologyLabel
var annotations map[string]string
// Add externalDNS annotation if necessary
extOpts := solrCloud.Spec.SolrAddressability.External
if extOpts != nil && extOpts.Method == solr.ExternalDNS && !extOpts.HideCommon {
annotations = make(map[string]string, 1)
urls := []string{solrCloud.ExternalDnsDomain(extOpts.DomainName)}
for _, domain := range extOpts.AdditionalDomainNames {
urls = append(urls, solrCloud.ExternalDnsDomain(domain))
}
annotations["external-dns.alpha.kubernetes.io/hostname"] = strings.Join(urls, ",")
}
customOptions := solrCloud.Spec.CustomSolrKubeOptions.CommonServiceOptions
if nil != customOptions {
labels = MergeLabelsOrAnnotations(labels, customOptions.Labels)
annotations = MergeLabelsOrAnnotations(annotations, customOptions.Annotations)
}
service := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: solrCloud.CommonServiceName(),
Namespace: solrCloud.GetNamespace(),
Labels: labels,
Annotations: annotations,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: SolrClientPortName,
Port: int32(solrCloud.Spec.SolrAddressability.CommonServicePort),
Protocol: corev1.ProtocolTCP,
TargetPort: intstr.FromString(SolrClientPortName),
AppProtocol: getAppProtocol(solrCloud),
},
},
Selector: selectorLabels,
},
}
return service
}
// GenerateHeadlessService returns a new Headless corev1.Service pointer generated for the SolrCloud instance
// The PublishNotReadyAddresses option is set as true, because we want each pod to be reachable no matter the readiness of the pod.
// solrCloud: SolrCloud instance
func GenerateHeadlessService(solrCloud *solr.SolrCloud) *corev1.Service {
labels := solrCloud.SharedLabelsWith(solrCloud.GetLabels())
labels["service-type"] = "headless"
selectorLabels := solrCloud.SharedLabels()
selectorLabels["technology"] = solr.SolrTechnologyLabel
var annotations map[string]string
// Add externalDNS annotation if necessary
extOpts := solrCloud.Spec.SolrAddressability.External
if extOpts != nil && extOpts.Method == solr.ExternalDNS && !extOpts.HideNodes {
annotations = make(map[string]string, 1)
urls := []string{solrCloud.ExternalDnsDomain(extOpts.DomainName)}
for _, domain := range extOpts.AdditionalDomainNames {
urls = append(urls, solrCloud.ExternalDnsDomain(domain))
}
annotations["external-dns.alpha.kubernetes.io/hostname"] = strings.Join(urls, ",")
}
customOptions := solrCloud.Spec.CustomSolrKubeOptions.HeadlessServiceOptions