This repository has been archived by the owner on Nov 7, 2019. It is now read-only.
/
operator.go
268 lines (235 loc) · 9.82 KB
/
operator.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
// >>>>>>> DO NOT EDIT THIS FILE <<<<<<<<<<
// This file is autogenerated via `aws-operator generate`
// If you'd like the change anything about this file make edits to the .templ
// file in the pkg/codegen/assets directory.
package elasticache
import (
"context"
"github.com/awslabs/aws-service-operator/pkg/helpers"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"reflect"
awsclient "github.com/awslabs/aws-service-operator/pkg/client/clientset/versioned/typed/service-operator.aws/v1alpha1"
"github.com/awslabs/aws-service-operator/pkg/config"
"github.com/awslabs/aws-service-operator/pkg/operator"
"github.com/awslabs/aws-service-operator/pkg/queue"
"github.com/awslabs/aws-service-operator/pkg/queuemanager"
"github.com/iancoleman/strcase"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/cache"
"strings"
awsV1alpha1 "github.com/awslabs/aws-service-operator/pkg/apis/service-operator.aws/v1alpha1"
)
// Operator represents a controller object for object store custom resources
type Operator struct {
config config.Config
topicARN string
queueManager *queuemanager.QueueManager
}
// NewOperator create controller for watching object store custom resources created
func NewOperator(config config.Config, queueManager *queuemanager.QueueManager) *Operator {
queuectrl := queue.New(config, config.AWSClientset, 10)
topicARN, _ := queuectrl.Register("elasticache")
queueManager.Add(topicARN, queuemanager.HandlerFunc(QueueUpdater))
return &Operator{
config: config,
topicARN: topicARN,
queueManager: queueManager,
}
}
// StartWatch watches for instances of Object Store custom resources and acts on them
func (c *Operator) StartWatch(ctx context.Context, namespace string) {
resourceHandlers := cache.ResourceEventHandlerFuncs{
AddFunc: c.onAdd,
UpdateFunc: c.onUpdate,
DeleteFunc: c.onDelete,
}
oper := operator.New("elasticaches", namespace, resourceHandlers, c.config.AWSClientset.RESTClient())
oper.Watch(&awsV1alpha1.ElastiCache{}, ctx.Done())
}
// QueueUpdater will take the messages from the queue and process them
func QueueUpdater(config config.Config, msg *queuemanager.MessageBody) error {
logger := config.Logger
var name, namespace string
if msg.Updatable {
name = msg.ResourceName
namespace = msg.Namespace
} else {
clientSet, _ := awsclient.NewForConfig(config.RESTConfig)
resources, err := clientSet.ElastiCaches("").List(metav1.ListOptions{})
if err != nil {
logger.WithError(err).Error("error getting elasticaches")
return err
}
for _, resource := range resources.Items {
if resource.Status.StackID == msg.ParsedMessage["StackId"] {
name = resource.Name
namespace = resource.Namespace
}
}
}
if name != "" && namespace != "" {
annotations := map[string]string{
"StackID": msg.ParsedMessage["StackId"],
"StackName": msg.ParsedMessage["StackName"],
"ResourceType": msg.ParsedMessage["ResourceType"],
}
if msg.ParsedMessage["ResourceStatus"] == "ROLLBACK_COMPLETE" {
obj, err := deleteStack(config, name, namespace, msg.ParsedMessage["StackId"])
if err != nil {
return err
}
config.Recorder.AnnotatedEventf(obj, annotations, corev1.EventTypeWarning, strcase.ToCamel(strings.ToLower(msg.ParsedMessage["ResourceStatus"])), msg.ParsedMessage["ResourceStatusReason"])
} else if msg.ParsedMessage["ResourceStatus"] == "DELETE_COMPLETE" {
obj, err := updateStatus(config, name, namespace, msg.ParsedMessage["StackId"], msg.ParsedMessage["ResourceStatus"], msg.ParsedMessage["ResourceStatusReason"])
if err != nil {
return err
}
config.Recorder.AnnotatedEventf(obj, annotations, corev1.EventTypeWarning, strcase.ToCamel(strings.ToLower(msg.ParsedMessage["ResourceStatus"])), msg.ParsedMessage["ResourceStatusReason"])
err = incrementRollbackCount(config, name, namespace)
if err != nil {
return err
}
} else {
obj, err := updateStatus(config, name, namespace, msg.ParsedMessage["StackId"], msg.ParsedMessage["ResourceStatus"], msg.ParsedMessage["ResourceStatusReason"])
if err != nil {
return err
}
config.Recorder.AnnotatedEventf(obj, annotations, corev1.EventTypeNormal, strcase.ToCamel(strings.ToLower(msg.ParsedMessage["ResourceStatus"])), msg.ParsedMessage["ResourceStatusReason"])
}
}
return nil
}
func (c *Operator) onAdd(obj interface{}) {
s := obj.(*awsV1alpha1.ElastiCache).DeepCopy()
if s.Status.ResourceStatus == "" || s.Status.ResourceStatus == "DELETE_COMPLETE" {
cft := New(c.config, s, c.topicARN)
output, err := cft.CreateStack()
if err != nil {
c.config.Logger.WithError(err).Errorf("error creating elasticache '%s'", s.Name)
return
}
c.config.Logger.Infof("added elasticache '%s' with stackID '%s'", s.Name, string(*output.StackId))
c.config.Logger.Infof("view at https://console.aws.amazon.com/cloudformation/home?#/stack/detail?stackId=%s", string(*output.StackId))
_, err = updateStatus(c.config, s.Name, s.Namespace, string(*output.StackId), "CREATE_IN_PROGRESS", "")
if err != nil {
c.config.Logger.WithError(err).Error("error updating status")
}
}
}
func (c *Operator) onUpdate(oldObj, newObj interface{}) {
oo := oldObj.(*awsV1alpha1.ElastiCache).DeepCopy()
no := newObj.(*awsV1alpha1.ElastiCache).DeepCopy()
if no.Status.ResourceStatus == "DELETE_COMPLETE" {
c.onAdd(no)
}
if helpers.IsStackComplete(oo.Status.ResourceStatus, false) && !reflect.DeepEqual(oo.Spec, no.Spec) {
cft := New(c.config, oo, c.topicARN)
output, err := cft.UpdateStack(no)
if err != nil {
c.config.Logger.WithError(err).Errorf("error updating elasticache '%s' with new params %+v and old %+v", no.Name, no, oo)
return
}
c.config.Logger.Infof("updated elasticache '%s' with params '%s'", no.Name, string(*output.StackId))
c.config.Logger.Infof("view at https://console.aws.amazon.com/cloudformation/home?#/stack/detail?stackId=%s", string(*output.StackId))
_, err = updateStatus(c.config, oo.Name, oo.Namespace, string(*output.StackId), "UPDATE_IN_PROGRESS", "")
if err != nil {
c.config.Logger.WithError(err).Error("error updating status")
}
}
}
func (c *Operator) onDelete(obj interface{}) {
s := obj.(*awsV1alpha1.ElastiCache).DeepCopy()
cft := New(c.config, s, c.topicARN)
err := cft.DeleteStack()
if err != nil {
c.config.Logger.WithError(err).Errorf("error deleting elasticache '%s'", s.Name)
return
}
c.config.Logger.Infof("deleted elasticache '%s'", s.Name)
}
func incrementRollbackCount(config config.Config, name string, namespace string) error {
logger := config.Logger
clientSet, _ := awsclient.NewForConfig(config.RESTConfig)
resource, err := clientSet.ElastiCaches(namespace).Get(name, metav1.GetOptions{})
if err != nil {
logger.WithError(err).Error("error getting elasticaches")
return err
}
resourceCopy := resource.DeepCopy()
resourceCopy.Spec.RollbackCount = resourceCopy.Spec.RollbackCount + 1
_, err = clientSet.ElastiCaches(namespace).Update(resourceCopy)
if err != nil {
logger.WithError(err).Error("error updating resource")
return err
}
return nil
}
func updateStatus(config config.Config, name string, namespace string, stackID string, status string, reason string) (*awsV1alpha1.ElastiCache, error) {
logger := config.Logger
clientSet, _ := awsclient.NewForConfig(config.RESTConfig)
resource, err := clientSet.ElastiCaches(namespace).Get(name, metav1.GetOptions{})
if err != nil {
logger.WithError(err).Error("error getting elasticaches")
return nil, err
}
resourceCopy := resource.DeepCopy()
resourceCopy.Status.ResourceStatus = status
resourceCopy.Status.ResourceStatusReason = reason
resourceCopy.Status.StackID = stackID
if helpers.IsStackComplete(status, false) {
cft := New(config, resourceCopy, "")
outputs, err := cft.GetOutputs()
if err != nil {
logger.WithError(err).Error("error getting outputs")
}
resourceCopy.Output.RedisEndpointAddress = outputs["RedisEndpointAddress"]
resourceCopy.Output.RedisEndpointPort = outputs["RedisEndpointPort"]
resourceCopy.Output.ConfigurationEndpointAddress = outputs["ConfigurationEndpointAddress"]
resourceCopy.Output.ConfigurationEndpointPort = outputs["ConfigurationEndpointPort"]
}
_, err = clientSet.ElastiCaches(namespace).Update(resourceCopy)
if err != nil {
logger.WithError(err).Error("error updating resource")
return nil, err
}
if helpers.IsStackComplete(status, false) {
err = syncAdditionalResources(config, resourceCopy)
if err != nil {
logger.WithError(err).Info("error syncing resources")
}
}
return resourceCopy, nil
}
func deleteStack(config config.Config, name string, namespace string, stackID string) (*awsV1alpha1.ElastiCache, error) {
logger := config.Logger
clientSet, _ := awsclient.NewForConfig(config.RESTConfig)
resource, err := clientSet.ElastiCaches(namespace).Get(name, metav1.GetOptions{})
if err != nil {
logger.WithError(err).Error("error getting elasticaches")
return nil, err
}
cft := New(config, resource, "")
err = cft.DeleteStack()
if err != nil {
return nil, err
}
err = cft.WaitUntilStackDeleted()
return resource, err
}
func syncAdditionalResources(config config.Config, s *awsV1alpha1.ElastiCache) (err error) {
clientSet, _ := awsclient.NewForConfig(config.RESTConfig)
resource, err := clientSet.ElastiCaches(s.Namespace).Get(s.Name, metav1.GetOptions{})
if err != nil {
return err
}
resource = resource.DeepCopy()
services := []string{}
elastiCacheAddressSvc := helpers.CreateExternalNameService(config, s, s.Name, s.Namespace, "{{ if .Obj.Output.RedisEndpointAddress }}{{ .Obj.Output.RedisEndpointAddress }}{{ else }}{{ .Obj.Output.ConfigurationEndpointAddress }}{{end}}", "{{ if .Obj.Output.RedisEndpointPort }}{{ .Obj.Output.RedisEndpointPort }}{{ else }}{{ .Obj.Output.ConfigurationEndpointPort }}{{end}}")
services = append(services, elastiCacheAddressSvc)
resource.AdditionalResources.Services = services
_, err = clientSet.ElastiCaches(s.Namespace).Update(resource)
if err != nil {
return err
}
return nil
}