-
Notifications
You must be signed in to change notification settings - Fork 604
/
Copy pathclusterimpl.go
2374 lines (2015 loc) · 79.9 KB
/
clusterimpl.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
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
package clusterservice
/*
Copyright 2017 - 2022 Crunchy Data Solutions, Inc.
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.
*/
import (
"errors"
"fmt"
"io/ioutil"
"strconv"
"strings"
"time"
"github.com/crunchydata/postgres-operator/internal/apiserver"
"github.com/crunchydata/postgres-operator/internal/apiserver/backupoptions"
"github.com/crunchydata/postgres-operator/internal/config"
"github.com/crunchydata/postgres-operator/internal/kubeapi"
"github.com/crunchydata/postgres-operator/internal/operator/backrest"
"github.com/crunchydata/postgres-operator/internal/util"
crv1 "github.com/crunchydata/postgres-operator/pkg/apis/crunchydata.com/v1"
msgs "github.com/crunchydata/postgres-operator/pkg/apiservermsgs"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/client-go/kubernetes"
)
const (
// ErrInvalidDataSource defines the error string that is displayed when the data source
// parameters for a create cluster request are invalid
ErrInvalidDataSource = "Unable to validate data source"
)
// DeleteCluster ...
func DeleteCluster(name, selector string, deleteData, deleteBackups bool, ns, pgouser string) msgs.DeleteClusterResponse {
var err error
response := msgs.DeleteClusterResponse{}
response.Status = msgs.Status{Code: msgs.Ok, Msg: ""}
response.Results = make([]string, 0)
if name != "all" {
if selector == "" {
selector = "name=" + name
}
}
log.Debugf("delete-data is [%t]", deleteData)
log.Debugf("delete-backups is [%t]", deleteBackups)
//get the clusters list
clusterList, err := apiserver.Clientset.CrunchydataV1().Pgclusters(ns).List(metav1.ListOptions{LabelSelector: selector})
if err != nil {
response.Status.Code = msgs.Error
response.Status.Msg = err.Error()
return response
}
if len(clusterList.Items) == 0 {
response.Status.Code = msgs.Error
response.Status.Msg = "no clusters found"
return response
}
for _, cluster := range clusterList.Items {
// check if the current cluster is not upgraded to the deployed
// Operator version. If not, do not allow the command to complete
if cluster.Annotations[config.ANNOTATION_IS_UPGRADED] == config.ANNOTATIONS_FALSE {
response.Status.Code = msgs.Error
response.Status.Msg = cluster.Name + msgs.UpgradeError
return response
}
log.Debugf("deleting cluster %s", cluster.Spec.Name)
taskName := cluster.Spec.Name + "-rmdata"
log.Debugf("creating taskName %s", taskName)
isBackup := false
isReplica := false
replicaName := ""
clusterPGHAScope := cluster.ObjectMeta.Labels[config.LABEL_PGHA_SCOPE]
// first delete any existing rmdata pgtask with the same name
err = apiserver.Clientset.CrunchydataV1().Pgtasks(ns).Delete(taskName, &metav1.DeleteOptions{})
if err != nil && !kerrors.IsNotFound(err) {
response.Status.Code = msgs.Error
response.Status.Msg = err.Error()
return response
}
err := apiserver.CreateRMDataTask(cluster.Spec.Name, replicaName, taskName, deleteBackups, deleteData, isReplica, isBackup, ns, clusterPGHAScope)
if err != nil {
log.Debugf("error on creating rmdata task %s", err.Error())
response.Status.Code = msgs.Error
response.Status.Msg = err.Error()
return response
}
response.Results = append(response.Results, "deleted pgcluster "+cluster.Spec.Name)
}
return response
}
// ShowCluster ...
func ShowCluster(name, selector, ccpimagetag, ns string, allflag bool) msgs.ShowClusterResponse {
var err error
response := msgs.ShowClusterResponse{}
response.Status = msgs.Status{Code: msgs.Ok, Msg: ""}
response.Results = make([]msgs.ShowClusterDetail, 0)
if selector == "" && allflag {
log.Debugf("allflags set to true")
} else {
if selector == "" {
selector = "name=" + name
}
}
log.Debugf("selector on showCluster is %s", selector)
//get a list of all clusters
clusterList, err := apiserver.Clientset.CrunchydataV1().Pgclusters(ns).List(metav1.ListOptions{LabelSelector: selector})
if err != nil {
response.Status.Code = msgs.Error
response.Status.Msg = err.Error()
return response
}
log.Debugf("clusters found len is %d", len(clusterList.Items))
for _, c := range clusterList.Items {
detail := msgs.ShowClusterDetail{}
detail.Cluster = c
detail.Deployments, err = getDeployments(&c, ns)
if err != nil {
response.Status.Code = msgs.Error
response.Status.Msg = err.Error()
return response
}
detail.Pods, err = GetPods(apiserver.Clientset, &c)
if err != nil {
response.Status.Code = msgs.Error
response.Status.Msg = err.Error()
return response
}
detail.Services, err = getServices(&c, ns)
if err != nil {
response.Status.Code = msgs.Error
response.Status.Msg = err.Error()
return response
}
detail.Replicas, err = getReplicas(&c, ns)
if err != nil {
response.Status.Code = msgs.Error
response.Status.Msg = err.Error()
return response
}
// capture whether or not the cluster is currently a standby cluster
detail.Standby = c.Spec.Standby
if ccpimagetag == "" {
response.Results = append(response.Results, detail)
} else if ccpimagetag == c.Spec.CCPImageTag {
response.Results = append(response.Results, detail)
}
}
return response
}
func getDeployments(cluster *crv1.Pgcluster, ns string) ([]msgs.ShowClusterDeployment, error) {
output := make([]msgs.ShowClusterDeployment, 0)
selector := config.LABEL_PG_CLUSTER + "=" + cluster.Spec.Name
deployments, err := apiserver.Clientset.
AppsV1().Deployments(ns).
List(metav1.ListOptions{LabelSelector: selector})
if err != nil {
return output, err
}
for _, dep := range deployments.Items {
d := msgs.ShowClusterDeployment{}
d.Name = dep.Name
d.PolicyLabels = make([]string, 0)
for k, v := range cluster.ObjectMeta.Labels {
if v == "pgpolicy" {
d.PolicyLabels = append(d.PolicyLabels, k)
}
}
output = append(output, d)
}
return output, err
}
func GetPods(clientset kubernetes.Interface, cluster *crv1.Pgcluster) ([]msgs.ShowClusterPod, error) {
output := []msgs.ShowClusterPod{}
//get pods, but exclude backup pods and backrest repo
selector := fmt.Sprintf("%s=%s,%s", config.LABEL_PG_CLUSTER, cluster.GetName(), config.LABEL_PG_DATABASE)
log.Debugf("selector for GetPods is %s", selector)
pods, err := clientset.CoreV1().Pods(cluster.Namespace).List(metav1.ListOptions{LabelSelector: selector})
if err != nil {
return output, err
}
for _, p := range pods.Items {
d := msgs.ShowClusterPod{
PVC: []msgs.ShowClusterPodPVC{},
}
d.Name = p.Name
d.Phase = string(p.Status.Phase)
d.NodeName = p.Spec.NodeName
d.ReadyStatus, d.Ready = getReadyStatus(&p)
// get information about several of the PVCs. This borrows from a legacy
// method to get this information
for _, v := range p.Spec.Volumes {
// if this volume is not a PVC, continue
if v.VolumeSource.PersistentVolumeClaim == nil {
continue
}
// if this is not any of the 3 mounted PVCs to a PostgreSQL Pod, continue
if !(v.Name == "pgdata" || v.Name == "pgwal-volume" || strings.HasPrefix(v.Name, "tablespace")) {
continue
}
pvcName := v.VolumeSource.PersistentVolumeClaim.ClaimName
// query the PVC to get the storage capacity
pvc, err := clientset.CoreV1().PersistentVolumeClaims(cluster.Namespace).Get(pvcName, metav1.GetOptions{})
// if there is an error, ignore it, and move on to the next one
if err != nil {
log.Warn(err)
continue
}
capacity := pvc.Status.Capacity[v1.ResourceStorage]
clusterPVCDetail := msgs.ShowClusterPodPVC{
Capacity: capacity.String(),
Name: pvcName,
}
d.PVC = append(d.PVC, clusterPVCDetail)
}
d.Primary = false
d.Type = getType(&p, cluster.Spec.Name)
if d.Type == msgs.PodTypePrimary {
d.Primary = true
}
output = append(output, d)
}
return output, err
}
func getServices(cluster *crv1.Pgcluster, ns string) ([]msgs.ShowClusterService, error) {
output := make([]msgs.ShowClusterService, 0)
selector := config.LABEL_PGO_BACKREST_REPO + "!=true," + config.LABEL_PG_CLUSTER + "=" + cluster.Spec.Name
services, err := apiserver.Clientset.CoreV1().Services(ns).List(metav1.ListOptions{LabelSelector: selector})
if err != nil {
return output, err
}
log.Debugf("got %d services for %s", len(services.Items), cluster.Spec.Name)
for _, p := range services.Items {
d := msgs.ShowClusterService{}
d.Name = p.Name
if strings.HasSuffix(p.Name, "-backrest-repo") {
d.BackrestRepo = true
d.ClusterName = cluster.Name
} else if strings.HasSuffix(p.Name, "-pgbouncer") {
d.Pgbouncer = true
d.ClusterName = cluster.Name
} else if strings.HasSuffix(p.Name, "-pgadmin") {
d.PGAdmin = true
d.ClusterName = cluster.Name
}
d.ClusterIP = p.Spec.ClusterIP
for _, port := range p.Spec.Ports {
d.ClusterPorts = append(d.ClusterPorts, strconv.Itoa(int(port.Port))+"/"+string(port.Protocol))
}
if len(p.Spec.ExternalIPs) > 0 {
d.ExternalIP = p.Spec.ExternalIPs[0]
}
if len(p.Status.LoadBalancer.Ingress) > 0 {
d.ExternalIP = p.Status.LoadBalancer.Ingress[0].IP
}
output = append(output, d)
}
return output, err
}
// TestCluster performs a variety of readiness checks against one or more
// clusters within a namespace. It leverages the following two Kubernetes
// constructs in order to determine the availability of PostgreSQL clusters:
// - Pod readiness checks. The Pod readiness checks leverage "pg_isready" to
// determine if the PostgreSQL cluster is able to accept connecions
// - Endpoint checks. The check sees if the services in front of the the
// PostgreSQL instances are able to route connections from the "outside" into
// the instances
func TestCluster(name, selector, ns, pgouser string, allFlag bool) msgs.ClusterTestResponse {
var err error
log.Debugf("TestCluster(%s,%s,%s,%s,%v): Called",
name, selector, ns, pgouser, allFlag)
response := msgs.ClusterTestResponse{}
response.Results = make([]msgs.ClusterTestResult, 0)
response.Status = msgs.Status{Code: msgs.Ok, Msg: ""}
log.Debugf("selector is: %s", selector)
// if the select is empty, determine if its because the flag for
// "all clusters" in a namespace is set
//
// otherwise, a name cluster name must be passed in, and said name should
// be used
if selector == "" {
if allFlag {
log.Debugf("selector is : all clusters in %s", ns)
} else {
selector = "name=" + name
log.Debugf("selector is: %s", selector)
}
}
// Find a list of a clusters that match the given selector
clusterList, err := apiserver.Clientset.CrunchydataV1().Pgclusters(ns).List(metav1.ListOptions{LabelSelector: selector})
// If the response errors, return here, as we won't be able to return any
// useful information in the test
if err != nil {
log.Errorf("Cluster lookup failed: %s", err.Error())
response.Status.Code = msgs.Error
response.Status.Msg = err.Error()
return response
}
log.Debugf("Total clusters found: %d", len(clusterList.Items))
// Iterate through each cluster and perform the various tests against them
for _, c := range clusterList.Items {
// Set up the object that will be appended to the response that
// indicates the availability of the endpoints / instances for this
// cluster
result := msgs.ClusterTestResult{
ClusterName: c.Name,
Endpoints: make([]msgs.ClusterTestDetail, 0),
Instances: make([]msgs.ClusterTestDetail, 0),
}
detail := msgs.ShowClusterDetail{}
detail.Cluster = c
// Get the PostgreSQL instances!
log.Debugf("Looking up instance pods for cluster: %s", c.Name)
pods, err := GetPrimaryAndReplicaPods(&c, ns)
// if there is an error with returning the primary/replica instances,
// then error and continue
if err != nil {
log.Errorf("Instance pod lookup failed: %s", err.Error())
instance := msgs.ClusterTestDetail{
Available: false,
InstanceType: msgs.ClusterTestInstanceTypePrimary,
}
result.Instances = append(result.Instances, instance)
response.Results = append(response.Results, result)
continue
}
log.Debugf("pods found %d", len(pods))
// if there are no pods found, then the cluster is not ready at all, and
// we can make an early on checking the availability of this cluster
if len(pods) == 0 {
log.Infof("Cluster has no instances available: %s", c.Name)
instance := msgs.ClusterTestDetail{
Available: false,
InstanceType: msgs.ClusterTestInstanceTypePrimary,
}
result.Instances = append(result.Instances, instance)
response.Results = append(response.Results, result)
continue
}
// Check each instance (i.e. pod) to see if its readiness check passes.
//
// (We are assuming that the readiness check is performing the
// equivalent to a "pg_isready" which denotes that a PostgreSQL instance
// is connectable. If you have any doubts about this, check the
// readiness check code)
//
// Also denotes the type of PostgreSQL instance this is. All of the pods
// returned are either primaries or replicas
for _, pod := range pods {
// set up the object with the instance status
instance := msgs.ClusterTestDetail{
Available: pod.Ready,
Message: pod.Name,
}
switch pod.Type {
default:
instance.InstanceType = msgs.ClusterTestInstanceTypeUnknown
case msgs.PodTypePrimary:
instance.InstanceType = msgs.ClusterTestInstanceTypePrimary
case msgs.PodTypeReplica:
instance.InstanceType = msgs.ClusterTestInstanceTypeReplica
}
log.Debugf("Instance found with attributes: (%s, %s, %v)",
instance.InstanceType, instance.Message, instance.Available)
// Add the report on the pods to this set
result.Instances = append(result.Instances, instance)
}
// Time to check the endpoints. We will check the available endpoints
// vis-a-vis the services
detail.Services, err = getServices(&c, ns)
// if the services are unavailable, report an error and continue
// iterating
if err != nil {
log.Errorf("Service lookup failed: %s", err.Error())
endpoint := msgs.ClusterTestDetail{
Available: false,
InstanceType: msgs.ClusterTestInstanceTypePrimary,
}
result.Endpoints = append(result.Endpoints, endpoint)
response.Results = append(response.Results, result)
continue
}
// Iterate through the services and determine if they are reachable via
// their endpionts
for _, service := range detail.Services {
// prepare the endpoint request
endpointRequest := &kubeapi.GetEndpointRequest{
Clientset: apiserver.Clientset, // current clientset
Name: service.Name, // name of the service, used to find the endpoint
Namespace: ns, // namespace the service / endpoint resides in
}
// prepare the end result, add the endpoint connection information
endpoint := msgs.ClusterTestDetail{
Message: fmt.Sprintf("%s:%s", service.ClusterIP, c.Spec.Port),
}
// determine the type of endpoint that is being checked based on
// the information available in the service
switch {
default:
endpoint.InstanceType = msgs.ClusterTestInstanceTypePrimary
case (strings.HasSuffix(service.Name, "-"+msgs.PodTypeReplica) && strings.Count(service.Name, "-"+msgs.PodTypeReplica) == 1):
endpoint.InstanceType = msgs.ClusterTestInstanceTypeReplica
case service.PGAdmin:
endpoint.InstanceType = msgs.ClusterTestInstanceTypePGAdmin
case service.Pgbouncer:
endpoint.InstanceType = msgs.ClusterTestInstanceTypePGBouncer
case service.BackrestRepo:
endpoint.InstanceType = msgs.ClusterTestInstanceTypeBackups
}
// make a call to the Kubernetes API to see if the endpoint exists
// if there is an error, indicate that this endpoint is inaccessible
// otherwise inspect the endpoint response to see if the Pods that
// comprise the Service are in the "NotReadyAddresses"
endpoint.Available = true
if endpointResponse, err := kubeapi.GetEndpoint(endpointRequest); err != nil {
endpoint.Available = false
} else {
for _, subset := range endpointResponse.Endpoint.Subsets {
// if any of the addresses are not ready in the endpoint,
// or there are no address ready, then the endpoint is not
// ready
if len(subset.NotReadyAddresses) > 0 && len(subset.Addresses) == 0 {
endpoint.Available = false
}
}
}
log.Debugf("Endpoint found with attributes: (%s, %s, %v)",
endpoint.InstanceType, endpoint.Message, endpoint.Available)
// append the endpoint to the list
result.Endpoints = append(result.Endpoints, endpoint)
}
// concaentate to the results and continue
response.Results = append(response.Results, result)
}
return response
}
// CreateCluster ...
// pgo create cluster mycluster
func CreateCluster(request *msgs.CreateClusterRequest, ns, pgouser string) msgs.CreateClusterResponse {
var id string
resp := msgs.CreateClusterResponse{
Result: msgs.CreateClusterDetail{},
Status: msgs.Status{
Code: msgs.Ok,
Msg: "",
},
}
clusterName := request.Name
if clusterName == "all" {
resp.Status.Code = msgs.Error
resp.Status.Msg = "invalid cluster name 'all' is not allowed as a cluster name"
return resp
}
if request.ReplicaCount < 0 {
resp.Status.Code = msgs.Error
resp.Status.Msg = "invalid replica-count , should be greater than or equal to 0"
return resp
}
errs := validation.IsDNS1035Label(clusterName)
if len(errs) > 0 {
resp.Status.Code = msgs.Error
resp.Status.Msg = "invalid cluster name format " + errs[0]
return resp
}
log.Debugf("create cluster called for %s", clusterName)
// error if it already exists
_, err := apiserver.Clientset.CrunchydataV1().Pgclusters(ns).Get(clusterName, metav1.GetOptions{})
if err == nil {
log.Debugf("pgcluster %s was found so we will not create it", clusterName)
resp.Status.Code = msgs.Error
resp.Status.Msg = "pgcluster " + clusterName + " was found so we will not create it"
return resp
} else if kerrors.IsNotFound(err) {
log.Debugf("pgcluster %s not found so we will create it", clusterName)
} else {
resp.Status.Code = msgs.Error
resp.Status.Msg = "error getting pgcluster " + clusterName + err.Error()
return resp
}
userLabelsMap, err := apiserver.ValidateLabel(request.UserLabels)
if err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
// validate any parameters provided to bootstrap the cluster from an existing data source
if err := validateDataSourceParms(request); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
// if any of the the PVCSizes are set to a customized value, ensure that they
// are recognizable by Kubernetes
// first, the primary/replica PVC size
if err := apiserver.ValidateQuantity(request.PVCSize); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = fmt.Sprintf(apiserver.ErrMessagePVCSize, request.PVCSize, err.Error())
return resp
}
// next, the pgBackRest repo PVC size
if err := apiserver.ValidateQuantity(request.BackrestPVCSize); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = fmt.Sprintf(apiserver.ErrMessagePVCSize, request.BackrestPVCSize, err.Error())
return resp
}
if err := apiserver.ValidateQuantity(request.WALPVCSize); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = fmt.Sprintf(apiserver.ErrMessagePVCSize, request.WALPVCSize, err.Error())
return resp
}
// evaluate if the CPU / Memory have been set to custom values and ensure the
// limit is set to valid bounds
zeroQuantity := resource.Quantity{}
if err := apiserver.ValidateResourceRequestLimit(request.CPURequest, request.CPULimit, zeroQuantity); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
if err := apiserver.ValidateResourceRequestLimit(request.MemoryRequest, request.MemoryLimit,
apiserver.Pgo.Cluster.DefaultInstanceResourceMemory); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
// similarly, if any of the pgBackRest repo CPU / Memory values have been set,
// evaluate those as well
if err := apiserver.ValidateResourceRequestLimit(request.BackrestCPURequest, request.BackrestCPULimit, zeroQuantity); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
if err := apiserver.ValidateResourceRequestLimit(request.BackrestMemoryRequest, request.BackrestMemoryLimit,
apiserver.Pgo.Cluster.DefaultBackrestResourceMemory); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
// similarly, if any of the pgBouncer CPU / Memory values have been set,
// evaluate those as well
if err := apiserver.ValidateResourceRequestLimit(request.PgBouncerCPURequest, request.PgBouncerCPULimit, zeroQuantity); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
if err := apiserver.ValidateResourceRequestLimit(request.PgBouncerMemoryRequest, request.PgBouncerMemoryLimit,
apiserver.Pgo.Cluster.DefaultPgBouncerResourceMemory); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
// similarly, if any of the Crunchy Postgres Exporter CPU / Memory values have been set,
// evaluate those as well
if err := apiserver.ValidateResourceRequestLimit(request.ExporterCPURequest, request.ExporterCPULimit, zeroQuantity); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
if err := apiserver.ValidateResourceRequestLimit(request.ExporterMemoryRequest, request.ExporterMemoryLimit,
apiserver.Pgo.Cluster.DefaultPgBouncerResourceMemory); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
// validate the storage type for each specified tablespace actually exists.
// if a PVCSize is passed in, also validate that it follows the Kubernetes
// format
if err := validateTablespaces(request.Tablespaces); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
// validate the TLS parameters for enabling TLS in a PostgreSQL cluster
if err := validateClusterTLS(request); err != nil {
log.Error(err)
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
if request.CustomConfig != "" {
found, err := validateCustomConfig(request.CustomConfig, ns)
if !found {
resp.Status.Code = msgs.Error
resp.Status.Msg = request.CustomConfig + " configmap was not found "
return resp
}
if err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
//add a label for the custom config
userLabelsMap[config.LABEL_CUSTOM_CONFIG] = request.CustomConfig
}
//set the metrics flag with the global setting first
userLabelsMap[config.LABEL_EXPORTER] = strconv.FormatBool(apiserver.MetricsFlag)
if err != nil {
log.Error(err)
}
//if metrics is chosen on the pgo command, stick it into the user labels
if request.MetricsFlag {
userLabelsMap[config.LABEL_EXPORTER] = "true"
}
if request.ServiceType != "" {
if request.ServiceType != config.DEFAULT_SERVICE_TYPE && request.ServiceType != config.LOAD_BALANCER_SERVICE_TYPE && request.ServiceType != config.NODEPORT_SERVICE_TYPE {
resp.Status.Code = msgs.Error
resp.Status.Msg = "error ServiceType should be either ClusterIP or LoadBalancer "
return resp
}
userLabelsMap[config.LABEL_SERVICE_TYPE] = request.ServiceType
}
// if the request is for a standby cluster then validate it to ensure all parameters have
// been properly specified as required to create a standby cluster
if request.Standby {
if err := validateStandbyCluster(request); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
}
// check that the specified ConfigMap exists
if request.BackrestConfig != "" {
_, err := apiserver.Clientset.CoreV1().ConfigMaps(ns).Get(request.BackrestConfig, metav1.GetOptions{})
if err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
}
// ensure the backrest storage type specified for the cluster is valid, and that the
// configuration required to use that storage type (e.g. a bucket, endpoint and region
// when using aws s3 storage) has been provided
err = validateBackrestStorageTypeOnCreate(request)
if err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
if request.BackrestStorageType != "" {
log.Debug("using backrest storage type provided by user")
userLabelsMap[config.LABEL_BACKREST_STORAGE_TYPE] = request.BackrestStorageType
}
// if a value for BackrestStorageConfig is provided, validate it here
if request.BackrestStorageConfig != "" && !apiserver.IsValidStorageName(request.BackrestStorageConfig) {
resp.Status.Code = msgs.Error
resp.Status.Msg = fmt.Sprintf("%q storage config was not found", request.BackrestStorageConfig)
return resp
}
log.Debug("userLabelsMap")
log.Debugf("%v", userLabelsMap)
if existsGlobalConfig(ns) {
userLabelsMap[config.LABEL_CUSTOM_CONFIG] = config.GLOBAL_CUSTOM_CONFIGMAP
}
if request.StorageConfig != "" && !apiserver.IsValidStorageName(request.StorageConfig) {
resp.Status.Code = msgs.Error
resp.Status.Msg = fmt.Sprintf("%q storage config was not found", request.StorageConfig)
return resp
}
if request.WALStorageConfig != "" && !apiserver.IsValidStorageName(request.WALStorageConfig) {
resp.Status.Code = msgs.Error
resp.Status.Msg = fmt.Sprintf("%q storage config was not found", request.WALStorageConfig)
return resp
}
if request.WALPVCSize != "" && request.WALStorageConfig == "" && apiserver.Pgo.WALStorage == "" {
resp.Status.Code = msgs.Error
resp.Status.Msg = "WAL size requires WAL storage"
return resp
}
// validate & parse nodeLabel if exists
if request.NodeLabel != "" {
if err = apiserver.ValidateNodeLabel(request.NodeLabel); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
parts := strings.Split(request.NodeLabel, "=")
userLabelsMap[config.LABEL_NODE_LABEL_KEY] = parts[0]
userLabelsMap[config.LABEL_NODE_LABEL_VALUE] = parts[1]
log.Debug("primary node labels used from user entered flag")
}
if request.ReplicaStorageConfig != "" {
if apiserver.IsValidStorageName(request.ReplicaStorageConfig) == false {
resp.Status.Code = msgs.Error
resp.Status.Msg = request.ReplicaStorageConfig + " Storage config was not found "
return resp
}
}
// if the pgBouncer flag is set, validate that replicas is set to a
// nonnegative value
if request.PgbouncerFlag && request.PgBouncerReplicas < 0 {
resp.Status.Code = msgs.Error
resp.Status.Msg = fmt.Sprintf(apiserver.ErrMessageReplicas+" for pgBouncer", 1)
return resp
}
// if a value is provided in the request for PodAntiAffinity, then ensure is valid. If
// it is, then set the user label for pod anti-affinity to the request value
// (which in turn becomes a *Label* which is important for anti-affinity).
// Otherwise, return the validation error.
if request.PodAntiAffinity != "" {
podAntiAffinityType := crv1.PodAntiAffinityType(request.PodAntiAffinity)
if err := podAntiAffinityType.Validate(); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
userLabelsMap[config.LABEL_POD_ANTI_AFFINITY] = request.PodAntiAffinity
} else {
userLabelsMap[config.LABEL_POD_ANTI_AFFINITY] = ""
}
// check to see if there are any pod anti-affinity overrides, specifically for
// pgBackRest and pgBouncer. If there are, ensure that they are valid values
if request.PodAntiAffinityPgBackRest != "" {
podAntiAffinityType := crv1.PodAntiAffinityType(request.PodAntiAffinityPgBackRest)
if err := podAntiAffinityType.Validate(); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
}
if request.PodAntiAffinityPgBouncer != "" {
podAntiAffinityType := crv1.PodAntiAffinityType(request.PodAntiAffinityPgBouncer)
if err := podAntiAffinityType.Validate(); err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
}
}
// if synchronous replication has been enabled, then add to user labels
if request.SyncReplication != nil {
userLabelsMap[config.LABEL_SYNC_REPLICATION] =
string(strconv.FormatBool(*request.SyncReplication))
}
// pgBackRest URI style must be set to either 'path' or 'host'. If it is neither,
// log an error and stop the cluster from being created.
if request.BackrestS3URIStyle != "" {
if request.BackrestS3URIStyle != "path" && request.BackrestS3URIStyle != "host" {
resp.Status.Code = msgs.Error
resp.Status.Msg = "pgBackRest S3 URI style must be set to either \"path\" or \"host\"."
return resp
}
}
// Create an instance of our CRD
newInstance := getClusterParams(request, clusterName, userLabelsMap, ns)
newInstance.ObjectMeta.Labels[config.LABEL_PGOUSER] = pgouser
if request.SecretFrom != "" {
err = validateSecretFrom(request.SecretFrom, newInstance.Spec.User, ns)
if err != nil {
resp.Status.Code = msgs.Error
resp.Status.Msg = request.SecretFrom + " secret was not found "
return resp
}
}
validateConfigPolicies(clusterName, request.Policies, ns)
// create the user secrets
// first, the superuser
if secretName, password, err := createUserSecret(request, newInstance, crv1.RootSecretSuffix,
crv1.PGUserSuperuser, request.PasswordSuperuser); err != nil {
log.Error(err)
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
} else {
newInstance.Spec.RootSecretName = secretName
// if the user requests to show system accounts, append it to the list
if request.ShowSystemAccounts {
user := msgs.CreateClusterDetailUser{
Username: crv1.PGUserSuperuser,
Password: password,
}
resp.Result.Users = append(resp.Result.Users, user)
}
}
// next, the replication user
if secretName, password, err := createUserSecret(request, newInstance, crv1.PrimarySecretSuffix,
crv1.PGUserReplication, request.PasswordReplication); err != nil {
log.Error(err)
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
} else {
newInstance.Spec.PrimarySecretName = secretName
// if the user requests to show system accounts, append it to the list
if request.ShowSystemAccounts {
user := msgs.CreateClusterDetailUser{
Username: crv1.PGUserReplication,
Password: password,
}
resp.Result.Users = append(resp.Result.Users, user)
}
}
// finally, the user from the request and/or default user
userSecretSuffix := fmt.Sprintf("-%s%s", newInstance.Spec.User, crv1.UserSecretSuffix)
if secretName, password, err := createUserSecret(request, newInstance, userSecretSuffix, newInstance.Spec.User,
request.Password); err != nil {
log.Error(err)
resp.Status.Code = msgs.Error
resp.Status.Msg = err.Error()
return resp
} else {
newInstance.Spec.UserSecretName = secretName
user := msgs.CreateClusterDetailUser{
Username: newInstance.Spec.User,
Password: password,
}
resp.Result.Users = append(resp.Result.Users, user)
}
// there's a secret for the monitoring user too
newInstance.Spec.CollectSecretName = clusterName + crv1.ExporterSecretSuffix
// Create Backrest secret for S3/SSH Keys:
// We make this regardless if backrest is enabled or not because
// the deployment template always tries to mount /sshd volume
secretName := fmt.Sprintf("%s-%s", clusterName, config.LABEL_BACKREST_REPO_SECRET)
// determine if a custom CA secret should be used
backrestS3CACert := []byte{}
if request.BackrestS3CASecretName != "" {
backrestSecret, err := apiserver.Clientset.
CoreV1().Secrets(request.Namespace).
Get(request.BackrestS3CASecretName, metav1.GetOptions{})
if err != nil {
log.Error(err)
resp.Status.Code = msgs.Error
resp.Status.Msg = fmt.Sprintf("Error finding pgBackRest S3 CA secret \"%s\": %s",
request.BackrestS3CASecretName, err.Error())
return resp
}
// attempt to retrieves the custom CA, assuming it has the name
// "aws-s3-ca.crt"
backrestS3CACert = backrestSecret.Data[util.BackRestRepoSecretKeyAWSS3KeyAWSS3CACert]
}
// save the S3 credentials in a single map so it can be used to either create a new
// secret or update an existing one
s3Credentials := map[string][]byte{
util.BackRestRepoSecretKeyAWSS3KeyAWSS3CACert: backrestS3CACert,
util.BackRestRepoSecretKeyAWSS3KeyAWSS3Key: []byte(request.BackrestS3Key),
util.BackRestRepoSecretKeyAWSS3KeyAWSS3KeySecret: []byte(request.BackrestS3KeySecret),
}