-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgclustercontroller.go
366 lines (308 loc) · 13.7 KB
/
pgclustercontroller.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
package pgcluster
/*
Copyright 2017 - 2020 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 (
"io/ioutil"
"reflect"
"strconv"
"strings"
"github.com/crunchydata/postgres-operator/internal/config"
"github.com/crunchydata/postgres-operator/internal/kubeapi"
backrestoperator "github.com/crunchydata/postgres-operator/internal/operator/backrest"
clusteroperator "github.com/crunchydata/postgres-operator/internal/operator/cluster"
"github.com/crunchydata/postgres-operator/internal/util"
crv1 "github.com/crunchydata/postgres-operator/pkg/apis/crunchydata.com/v1"
informers "github.com/crunchydata/postgres-operator/pkg/generated/informers/externalversions/crunchydata.com/v1"
log "github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
)
// Controller holds the connections for the controller
type Controller struct {
PgclusterClient *rest.RESTClient
PgclusterClientset kubernetes.Interface
PgclusterConfig *rest.Config
Queue workqueue.RateLimitingInterface
Informer informers.PgclusterInformer
PgclusterWorkerCount int
}
// onAdd is called when a pgcluster is added
func (c *Controller) onAdd(obj interface{}) {
cluster := obj.(*crv1.Pgcluster)
log.Debugf("[pgcluster Controller] ns %s onAdd %s", cluster.ObjectMeta.Namespace, cluster.ObjectMeta.SelfLink)
//handle the case when the operator restarts and don't
//process already processed pgclusters
if cluster.Status.State == crv1.PgclusterStateProcessed {
log.Debug("pgcluster " + cluster.ObjectMeta.Name + " already processed")
return
}
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
log.Debugf("cluster putting key in queue %s", key)
c.Queue.Add(key)
}
}
// RunWorker is a long-running function that will continually call the
// processNextWorkItem function in order to read and process a message on the
// workqueue.
func (c *Controller) RunWorker(stopCh <-chan struct{}, doneCh chan<- struct{}) {
go c.waitForShutdown(stopCh)
for c.processNextItem() {
}
log.Debug("pgcluster Contoller: worker queue has been shutdown, writing to the done channel")
doneCh <- struct{}{}
}
// waitForShutdown waits for a message on the stop channel and then shuts down the work queue
func (c *Controller) waitForShutdown(stopCh <-chan struct{}) {
<-stopCh
c.Queue.ShutDown()
log.Debug("pgcluster Contoller: received stop signal, worker queue told to shutdown")
}
func (c *Controller) processNextItem() bool {
// Wait until there is a new item in the working queue
key, quit := c.Queue.Get()
if quit {
return false
}
log.Debugf("working on %s", key.(string))
keyParts := strings.Split(key.(string), "/")
keyNamespace := keyParts[0]
keyResourceName := keyParts[1]
log.Debugf("cluster add queue got key ns=[%s] resource=[%s]", keyNamespace, keyResourceName)
// Tell the queue that we are done with processing this key. This unblocks the key for other workers
// This allows safe parallel processing because two pods with the same key are never processed in
// parallel.
defer c.Queue.Done(key)
// Invoke the method containing the business logic
// in this case, the de-dupe logic is to test whether a cluster
// deployment exists , if so, then we don't create another
_, err := c.PgclusterClientset.AppsV1().Deployments(keyNamespace).Get(keyResourceName, metav1.GetOptions{})
if err == nil {
log.Debugf("cluster add - dep already found, not creating again")
c.Queue.Forget(key)
return true
}
//get the pgcluster
cluster := crv1.Pgcluster{}
found, err := kubeapi.Getpgcluster(c.PgclusterClient, &cluster, keyResourceName, keyNamespace)
if !found {
log.Debugf("cluster add - pgcluster not found, this is invalid")
c.Queue.Forget(key) // NB(cbandy): This should probably be a retry.
return true
}
addIdentifier(&cluster)
// If bootstrapping from an existing data source then attempt to create the pgBackRest repository.
// If a repo already exists (e.g. because it is associated with a currently running cluster) then
// proceed with bootstrapping.
if cluster.Spec.PGDataSource.RestoreFrom != "" {
repoCreated, err := clusteroperator.AddBootstrapRepo(c.PgclusterClientset, c.PgclusterClient,
&cluster)
if err != nil {
log.Error(err)
c.Queue.AddRateLimited(key)
return true
}
// if no errors and no repo was created, then we know that the repo is for a currently running
// cluster and we can therefore proceed with bootstrapping.
if !repoCreated {
if err := clusteroperator.AddClusterBootstrap(c.PgclusterClientset, c.PgclusterClient,
&cluster); err != nil {
log.Error(err)
c.Queue.AddRateLimited(key)
return true
}
}
c.Queue.Forget(key)
return true
}
state := crv1.PgclusterStateProcessed
message := "Successfully processed Pgcluster by controller"
err = kubeapi.PatchpgclusterStatus(c.PgclusterClient, state, message, &cluster, keyNamespace)
if err != nil {
log.Errorf("ERROR updating pgcluster status on add: %s", err.Error())
c.Queue.Forget(key) // NB(cbandy): This should probably be a retry.
return true
}
log.Debugf("pgcluster added: %s", cluster.ObjectMeta.Name)
// AddClusterBase creates all deployments for the cluster (in addition to various other supporting
// resources such as services, configMaps, secrets, etc.), but leaves them scaled to 0. This
// ensures all deployments exist as needed to properly orchestrate initialization of the
// cluster, e.g. we need to ensure the primary DB deployment resource has been created before
// bringing the repo deployment online, since that in turn will bring the primary DB online.
clusteroperator.AddClusterBase(c.PgclusterClientset, c.PgclusterClient, &cluster, cluster.ObjectMeta.Namespace)
c.Queue.Forget(key)
return true
}
// onUpdate is called when a pgcluster is updated
func (c *Controller) onUpdate(oldObj, newObj interface{}) {
oldcluster := oldObj.(*crv1.Pgcluster)
newcluster := newObj.(*crv1.Pgcluster)
log.Debugf("pgcluster onUpdate for cluster %s (namespace %s)", newcluster.ObjectMeta.Namespace,
newcluster.ObjectMeta.Name)
// if the status of the pgcluster shows that it has been bootstrapped, then proceed with
// creating the cluster (i.e. the cluster deployment, services, etc.)
if newcluster.Status.State == crv1.PgclusterStateBootstrapped {
clusteroperator.AddClusterBase(c.PgclusterClientset, c.PgclusterClient, newcluster,
newcluster.GetNamespace())
return
}
// if the 'shutdown' parameter in the pgcluster update shows that the cluster should be either
// shutdown or started but its current status does not properly reflect that it is, then
// proceed with the logic needed to either shutdown or start the cluster
if newcluster.Spec.Shutdown && newcluster.Status.State != crv1.PgclusterStateShutdown {
clusteroperator.ShutdownCluster(c.PgclusterClientset, c.PgclusterClient, *newcluster)
} else if !newcluster.Spec.Shutdown &&
newcluster.Status.State == crv1.PgclusterStateShutdown {
clusteroperator.StartupCluster(c.PgclusterClientset, *newcluster)
}
// check to see if the "autofail" label on the pgcluster CR has been changed from either true to false, or from
// false to true. If it has been changed to false, autofail will then be disabled in the pg cluster. If has
// been changed to true, autofail will then be enabled in the pg cluster
if newcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL] != "" {
autofailEnabledOld, err := strconv.ParseBool(oldcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL])
if err != nil {
log.Error(err)
return
}
autofailEnabledNew, err := strconv.ParseBool(newcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL])
if err != nil {
log.Error(err)
return
}
if autofailEnabledNew != autofailEnabledOld {
util.ToggleAutoFailover(c.PgclusterClientset, autofailEnabledNew,
newcluster.ObjectMeta.Labels[config.LABEL_PGHA_SCOPE],
newcluster.ObjectMeta.Namespace)
}
}
// handle standby being enabled and disabled for the cluster
if oldcluster.Spec.Standby && !newcluster.Spec.Standby {
if err := clusteroperator.DisableStandby(c.PgclusterClientset, *newcluster); err != nil {
log.Error(err)
return
}
} else if !oldcluster.Spec.Standby && newcluster.Spec.Standby {
if err := clusteroperator.EnableStandby(c.PgclusterClientset, *newcluster); err != nil {
log.Error(err)
return
}
}
// see if any of the resource values have changed, and if so, update them
if !reflect.DeepEqual(oldcluster.Spec.Resources, newcluster.Spec.Resources) ||
!reflect.DeepEqual(oldcluster.Spec.Limits, newcluster.Spec.Limits) {
if err := clusteroperator.UpdateResources(c.PgclusterClientset, c.PgclusterConfig, newcluster); err != nil {
log.Error(err)
return
}
}
// see if any of the pgBackRest repository resource values have changed, and
// if so, update them
if !reflect.DeepEqual(oldcluster.Spec.BackrestResources, newcluster.Spec.BackrestResources) ||
!reflect.DeepEqual(oldcluster.Spec.BackrestLimits, newcluster.Spec.BackrestLimits) {
if err := backrestoperator.UpdateResources(c.PgclusterClientset, c.PgclusterConfig, newcluster); err != nil {
log.Error(err)
return
}
}
// see if any of the pgBouncer values have changed, and if so, update the
// pgBouncer deployment
if !reflect.DeepEqual(oldcluster.Spec.PgBouncer, newcluster.Spec.PgBouncer) {
if err := updatePgBouncer(c, oldcluster, newcluster); err != nil {
log.Error(err)
return
}
}
// if we are not in a standby state, check to see if the tablespaces have
// differed, and if so, add the additional volumes to the primary and replicas
if !reflect.DeepEqual(oldcluster.Spec.TablespaceMounts, newcluster.Spec.TablespaceMounts) {
if err := updateTablespaces(c, oldcluster, newcluster); err != nil {
log.Error(err)
return
}
}
}
// onDelete is called when a pgcluster is deleted
func (c *Controller) onDelete(obj interface{}) {
//cluster := obj.(*crv1.Pgcluster)
// log.Debugf("[Controller] ns=%s onDelete %s", cluster.ObjectMeta.Namespace, cluster.ObjectMeta.SelfLink)
//handle pgcluster cleanup
// clusteroperator.DeleteClusterBase(c.PgclusterClientset, c.PgclusterClient, cluster, cluster.ObjectMeta.Namespace)
}
// AddPGClusterEventHandler adds the pgcluster event handler to the pgcluster informer
func (c *Controller) AddPGClusterEventHandler() {
c.Informer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.onAdd,
UpdateFunc: c.onUpdate,
DeleteFunc: c.onDelete,
})
log.Debugf("pgcluster Controller: added event handler to informer")
}
func addIdentifier(clusterCopy *crv1.Pgcluster) {
u, err := ioutil.ReadFile("/proc/sys/kernel/random/uuid")
if err != nil {
log.Error(err)
}
clusterCopy.ObjectMeta.Labels[config.LABEL_PG_CLUSTER_IDENTIFIER] = string(u[:len(u)-1])
}
// updatePgBouncer updates the pgBouncer Deployment to reflect any changes that
// may be made, which include:
// - enabling a pgBouncer Deployment :)
// - disabling a pgBouncer Deployment :(
// - any changes to the resizing, etc.
func updatePgBouncer(c *Controller, oldCluster *crv1.Pgcluster, newCluster *crv1.Pgcluster) error {
log.Debugf("update pgbouncer for cluster %s", newCluster.Name)
// first, handle the easy ones, i.e. determine if we are enabling or disabling
if oldCluster.Spec.PgBouncer.Enabled() != newCluster.Spec.PgBouncer.Enabled() {
log.Debugf("pgbouncer enabled: %t", newCluster.Spec.PgBouncer.Enabled())
// if this is being enabled, it's a simple step where we can return here
if newCluster.Spec.PgBouncer.Enabled() {
return clusteroperator.AddPgbouncer(c.PgclusterClientset, c.PgclusterClient, c.PgclusterConfig, newCluster)
}
// if we're not enabled, we're disabled
return clusteroperator.DeletePgbouncer(c.PgclusterClientset, c.PgclusterClient, c.PgclusterConfig, newCluster)
}
// otherwise, this is an update
return clusteroperator.UpdatePgbouncer(c.PgclusterClientset, c.PgclusterClient, oldCluster, newCluster)
}
// updateTablespaces updates the PostgreSQL instance Deployments to reflect the
// new PostgreSQL tablespaces that should be added
func updateTablespaces(c *Controller, oldCluster *crv1.Pgcluster, newCluster *crv1.Pgcluster) error {
// to help the Operator function do less work, we will get a list of new
// tablespaces. Though these are already present in the CRD, this will isolate
// exactly which PVCs need to be created
//
// To do this, iterate through the the tablespace mount map that is present in
// the new cluster.
newTablespaces := map[string]crv1.PgStorageSpec{}
for tablespaceName, storageSpec := range newCluster.Spec.TablespaceMounts {
// if the tablespace does not exist in the old version of the cluster,
// then add it in!
if _, ok := oldCluster.Spec.TablespaceMounts[tablespaceName]; !ok {
log.Debugf("new tablespace found: [%s]", tablespaceName)
newTablespaces[tablespaceName] = storageSpec
}
}
// alright, update the tablespace entries for this cluster!
// if it returns an error, pass the error back up to the caller
if err := clusteroperator.UpdateTablespaces(c.PgclusterClientset, c.PgclusterConfig, newCluster, newTablespaces); err != nil {
return err
}
return nil
}
// WorkerCount returns the worker count for the controller
func (c *Controller) WorkerCount() int {
return c.PgclusterWorkerCount
}