-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathcluster.go
More file actions
417 lines (356 loc) · 11.8 KB
/
Copy pathcluster.go
File metadata and controls
417 lines (356 loc) · 11.8 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
/*
Copyright 2023 The Cockroach 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
https://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 resource
import (
"fmt"
"os"
"strings"
"time"
"github.com/Masterminds/semver/v3"
api "github.com/cockroachdb/cockroach-operator/apis/v1alpha1"
"github.com/cockroachdb/cockroach-operator/pkg/clusterstatus"
"github.com/cockroachdb/cockroach-operator/pkg/condition"
"github.com/cockroachdb/errors"
"github.com/gosimple/slug"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
const (
RELATED_IMAGE_PREFIX = "RELATED_IMAGE_COCKROACH_"
NotSupportedVersion = "not_supported_version"
CrdbContainerImageAnnotation = "crdb.io/containerimage"
CrdbVersionAnnotation = "crdb.io/version"
CrdbHistoryAnnotation = "crdb.io/history"
CrdbRestartAnnotation = "crdb.io/restart"
CrdbCertExpirationAnnotation = "crdb.io/certexpiration"
CrdbRestartTypeAnnotation = "crdb.io/restarttype"
VersionCheckJobName = "vcheck"
)
func NewCluster(original *api.CrdbCluster) Cluster {
cr := original.DeepCopy()
cr.Default()
timeNow := metav1.Now()
condition.InitConditionsIfNeeded(&cr.Status, timeNow)
clusterstatus.InitOperatorActionsIfNeeded(&cr.Status, timeNow)
return Cluster{
cr: cr,
initTime: timeNow,
}
}
func ClusterPlaceholder(name string) *api.CrdbCluster {
return &api.CrdbCluster{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
}
}
type Cluster struct {
Fetcher
cr *api.CrdbCluster
initTime metav1.Time
}
func (cluster Cluster) Unwrap() *api.CrdbCluster {
return cluster.cr.DeepCopy()
}
func (cluster Cluster) SetTrue(ctype api.ClusterConditionType) {
condition.SetTrue(ctype, &cluster.cr.Status, cluster.InitTime())
}
// True checks if the api.ClusterConditionType is true
func (cluster Cluster) True(ctype api.ClusterConditionType) bool {
return condition.True(ctype, cluster.cr.Status.Conditions)
}
func (cluster Cluster) SetClusterStatusOnFirstReconcile() {
clusterstatus.SetClusterStatusOnFirstReconcile(&cluster.cr.Status)
}
func (cluster Cluster) SetClusterStatus() {
clusterstatus.SetClusterStatus(&cluster.cr.Status)
}
func (cluster Cluster) SetClusterVersion(version string) {
cluster.cr.Status.Version = version
}
func (cluster Cluster) SetSQLHost(host string) {
cluster.cr.Status.SQLHost = host
}
func (cluster Cluster) SetCrdbContainerImage(containerimage string) {
cluster.cr.Status.CrdbContainerImage = containerimage
}
func (cluster Cluster) SetActionFailed(atype api.ActionType, errMsg string) {
clusterstatus.SetActionFailed(atype, errMsg, &cluster.cr.Status)
}
func (cluster Cluster) ResetActionType(atype api.ActionType) {
clusterstatus.ResetActionType(atype, &cluster.cr.Status)
}
func (cluster Cluster) SetActionFinished(atype api.ActionType) {
clusterstatus.SetActionFinished(atype, &cluster.cr.Status)
}
func (cluster Cluster) SetActionUnknown(atype api.ActionType) {
clusterstatus.SetActionUnknown(atype, &cluster.cr.Status)
}
func (cluster Cluster) Failed(atype api.ActionType) bool {
return clusterstatus.Failed(atype, cluster.Status().OperatorActions)
}
func (cluster Cluster) SetFalse(ctype api.ClusterConditionType) {
condition.SetFalse(ctype, &cluster.cr.Status, cluster.InitTime())
}
func (cluster Cluster) Spec() *api.CrdbClusterSpec {
return cluster.cr.Spec.DeepCopy()
}
func (cluster Cluster) Status() *api.CrdbClusterStatus {
return cluster.cr.Status.DeepCopy()
}
func (cluster Cluster) Name() string {
return cluster.cr.Name
}
func (cluster Cluster) Namespace() string {
return cluster.cr.Namespace
}
func (cluster Cluster) ObjectKey() types.NamespacedName {
return types.NamespacedName{Namespace: cluster.Namespace(), Name: cluster.Name()}
}
func (cluster Cluster) InitTime() metav1.Time {
return cluster.initTime
}
func (cluster Cluster) DiscoveryServiceName() string {
return cluster.Name()
}
func (cluster Cluster) RoleName() string {
return fmt.Sprintf("%s-role", cluster.Name())
}
func (cluster Cluster) RoleBindingName() string {
return cluster.RoleName() + "-binding"
}
func (cluster Cluster) PublicServiceName() string {
return fmt.Sprintf("%s-public", cluster.Name())
}
// PublicServiceAddress is the FQDN of the public service.
// E.g. <name>-public.namespace.svc.cluster.local
func (cluster Cluster) PublicServiceAddress() string {
return fmt.Sprintf(
"%s.%s.%s",
cluster.PublicServiceName(),
cluster.Namespace(),
cluster.Domain(),
)
}
func (cluster Cluster) ServiceAccountName() string {
return fmt.Sprintf("%s-sa", cluster.Name())
}
func (cluster Cluster) StatefulSetName() string {
return cluster.Name()
}
func (cluster Cluster) JobName() string {
slug.MaxLength = 63
return slug.Make(fmt.Sprintf("%s-%s-%d", cluster.Name(), VersionCheckJobName, getTimeHashInMinutes(time.Now())))
}
func (cluster Cluster) IngressSuffix() string {
return cluster.Name()
}
func getTimeHashInMinutes(scheduledTime time.Time) int64 {
return scheduledTime.Unix() / 60
}
func (cluster Cluster) IsSupportedImage() bool {
image := cluster.GetCockroachDBImageName()
return !strings.EqualFold(image, NotSupportedVersion)
}
func (cluster Cluster) LookupSupportedVersion(version string) (string, bool) {
if version == "" {
return "", false
}
supportedVersions := getSupportedCrdbVersions()
for _, v := range supportedVersions {
if strings.EqualFold(version, v) {
return v, true
}
}
return "", false
}
//GetVersionAnnotation gets the current version of the cluster retrieved by version checker action
func (cluster Cluster) GetVersionAnnotation() string {
return cluster.getAnnotation(CrdbVersionAnnotation)
}
func (cluster Cluster) GetAnnotationContainerImage() string {
return cluster.getAnnotation(CrdbContainerImageAnnotation)
}
func (cluster Cluster) GetAnnotationRestartType() string {
return cluster.getAnnotation(CrdbRestartTypeAnnotation)
}
func (cluster Cluster) GetAnnotationHistory() string {
return cluster.getAnnotation(CrdbHistoryAnnotation)
}
func (cluster Cluster) getAnnotation(key string) string {
if val, ok := cluster.cr.Annotations[key]; !ok {
return ""
} else {
return val
}
}
func (cluster Cluster) SetAnnotationVersion(version string) {
if cluster.cr.Annotations == nil {
cluster.cr.Annotations = make(map[string]string)
}
cluster.cr.Annotations[CrdbVersionAnnotation] = version
}
func (cluster Cluster) SetAnnotationContainerImage(containerimage string) {
if cluster.cr.Annotations == nil {
cluster.cr.Annotations = make(map[string]string)
}
cluster.cr.Annotations[CrdbContainerImageAnnotation] = containerimage
}
func (cluster Cluster) SetAnnotationCertExpiration(certExpiration string) {
if cluster.cr.Annotations == nil {
cluster.cr.Annotations = make(map[string]string)
}
cluster.cr.Annotations[CrdbCertExpirationAnnotation] = certExpiration
}
func (cluster Cluster) SetRestartTypeAnnotation(restartType string) {
if cluster.cr.Annotations == nil {
cluster.cr.Annotations = make(map[string]string)
}
cluster.cr.Annotations[CrdbRestartTypeAnnotation] = restartType
}
func (cluster Cluster) DeleteRestartTypeAnnotation() {
if cluster.cr.Annotations == nil {
return
}
delete(cluster.cr.Annotations, CrdbRestartTypeAnnotation)
}
func (cluster Cluster) GetCockroachDBImageName() string {
supportedImages := getSupportedCrdbImages()
if cluster.Spec().CockroachDBVersion != "" {
if version, ok := cluster.LookupSupportedVersion(cluster.Spec().CockroachDBVersion); ok {
if version == "" {
return NotSupportedVersion
}
if image, ok := supportedImages[version]; ok {
if image == "" {
return NotSupportedVersion
}
return image
}
}
return NotSupportedVersion
}
//we validate the version after the job runs with exec
return cluster.Spec().Image.Name
}
func (cluster Cluster) GetImagePullPolicy() corev1.PullPolicy {
if cluster.Spec().Image == nil || cluster.Spec().Image.PullPolicyName == nil {
return corev1.PullIfNotPresent
}
return *cluster.Spec().Image.PullPolicyName
}
func (cluster Cluster) GetImagePullSecret() *string {
if cluster.Spec().Image == nil {
return nil
}
return cluster.Spec().Image.PullSecret
}
func (cluster Cluster) NodeTLSSecretName() string {
if cluster.Spec().NodeTLSSecret != "" {
return cluster.Spec().NodeTLSSecret
}
return fmt.Sprintf("%s-node", cluster.Name())
}
func (cluster Cluster) ClientTLSSecretName(user string) string {
if cluster.Spec().ClientTLSSecret != "" {
return cluster.Spec().ClientTLSSecret
}
return fmt.Sprintf("%s-%s", cluster.Name(), user)
}
func (cluster Cluster) CASecretName() string {
return fmt.Sprintf("%s-ca", cluster.Name())
}
func (cluster Cluster) Domain() string {
return "svc.cluster.local"
}
func (cluster Cluster) SecureMode() string {
if cluster.Spec().TLSEnabled {
return "--certs-dir=/cockroach/cockroach-certs/"
}
return "--insecure"
}
func (cluster Cluster) LoggingConfiguration(fetcher Fetcher) (string, error) {
if cluster.Spec().LogConfigMap != "" {
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: cluster.Spec().LogConfigMap,
},
}
err := fetcher.Fetch(cm)
if err != nil {
return "", err
}
if val, ok := cm.Data["logging.yaml"]; ok {
return `"` + val + `"`, nil
} else {
return "", errors.Newf(
"`logging.yaml` entry not found in configMap %s", cluster.Spec().LogConfigMap)
}
}
return "\"{sinks: {stderr: {channels: [OPS, HEALTH], redact: true}}}\"", nil
}
func (cluster Cluster) IsLoggingAPIEnabled() bool {
var version string
if cluster.Spec().CockroachDBVersion != "" {
version = cluster.Spec().CockroachDBVersion
} else if cluster.Spec().Image != nil && cluster.Spec().Image.Name != "" {
version = strings.Split(cluster.Spec().Image.Name, ":")[1]
} else {
return false
}
// No need to handle the error as the version provided is constant
c, _ := semver.NewConstraint(">= v21.1")
v, err := semver.NewVersion(version)
if err != nil {
return false
}
return c.Check(v)
}
// TODO add error handling to ensure that env variables are set correctly and
// that we have a min number of them
// getSupportedCrdbImages will dynamic build an slice using the env var added in the operator.yaml
// We will add all the env var that start with RELATED_IMAGE
func getSupportedCrdbImages() map[string]string {
crdbSupportedImages := make(map[string]string)
supportedVersions := getSupportedCrdbVersions()
for _, v := range supportedVersions {
envVar := fmt.Sprintf("%s%s", RELATED_IMAGE_PREFIX, strings.ReplaceAll(v, ".", "_"))
crdbSupportedImages[v] = os.Getenv(envVar)
}
return crdbSupportedImages
}
func getSupportedCrdbVersions() []string {
supportedVersions := make([]string, 0)
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
if strings.HasPrefix(pair[0], RELATED_IMAGE_PREFIX) {
version := strings.ReplaceAll(pair[0], RELATED_IMAGE_PREFIX, "")
version = strings.ReplaceAll(version, "_", ".")
supportedVersions = append(supportedVersions, version)
}
}
return supportedVersions
}
// IsIngressNeeded returns true if ingress config is given in spec
func (cluster Cluster) IsIngressNeeded() bool {
return cluster.Spec().Ingress != nil
}
// IsUIIngressEnabled returns true if ingress config is given for UI
func (cluster Cluster) IsUIIngressEnabled() bool {
return cluster.Spec().Ingress != nil && cluster.Spec().Ingress.UI != nil
}
// IsSQLIngressEnabled returns true if ingress config is given for SQL
func (cluster Cluster) IsSQLIngressEnabled() bool {
return cluster.Spec().Ingress != nil && cluster.Spec().Ingress.SQL != nil
}