forked from amazon-archives/aws-service-operator
-
Notifications
You must be signed in to change notification settings - Fork 2
/
controller.go
267 lines (234 loc) · 8.64 KB
/
controller.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
// >>>>>>> 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 snstopic
import (
"github.com/awslabs/aws-service-operator/pkg/helpers"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"reflect"
"github.com/awslabs/aws-service-operator/pkg/config"
"github.com/awslabs/aws-service-operator/pkg/queue"
opkit "github.com/christopherhein/operator-kit"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/client-go/tools/cache"
awsapi "github.com/awslabs/aws-service-operator/pkg/apis/service-operator.aws"
awsV1alpha1 "github.com/awslabs/aws-service-operator/pkg/apis/service-operator.aws/v1alpha1"
awsclient "github.com/awslabs/aws-service-operator/pkg/client/clientset/versioned/typed/service-operator.aws/v1alpha1"
)
// Resource is the object store definition
var Resource = opkit.CustomResource{
Name: "snstopic",
Plural: "snstopics",
Group: awsapi.GroupName,
Version: awsapi.Version,
Scope: apiextensionsv1beta1.NamespaceScoped,
Kind: reflect.TypeOf(awsV1alpha1.SNSTopic{}).Name(),
ShortNames: []string{
"sns",
"topic",
"topics",
},
}
// Controller represents a controller object for object store custom resources
type Controller struct {
config *config.Config
context *opkit.Context
awsclientset awsclient.ServiceoperatorV1alpha1Interface
topicARN string
}
// NewController create controller for watching object store custom resources created
func NewController(config *config.Config, context *opkit.Context, awsclientset awsclient.ServiceoperatorV1alpha1Interface) *Controller {
return &Controller{
config: config,
context: context,
awsclientset: awsclientset,
}
}
// StartWatch watches for instances of Object Store custom resources and acts on them
func (c *Controller) StartWatch(namespace string, stopCh chan struct{}) error {
resourceHandlers := cache.ResourceEventHandlerFuncs{
AddFunc: c.onAdd,
UpdateFunc: c.onUpdate,
DeleteFunc: c.onDelete,
}
queuectrl := queue.New(c.config, c.context, c.awsclientset, 1)
c.topicARN, _, _, _ = queuectrl.Register("snstopic", &awsV1alpha1.SNSTopic{})
go queuectrl.StartWatch(queue.HandlerFunc(QueueUpdater), stopCh)
restClient := c.awsclientset.RESTClient()
watcher := opkit.NewWatcher(Resource, namespace, resourceHandlers, restClient)
go watcher.Watch(&awsV1alpha1.SNSTopic{}, stopCh)
return nil
}
// QueueUpdater will take the messages from the queue and process them
func QueueUpdater(config *config.Config, msg *queue.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.SNSTopics("").List(metav1.ListOptions{})
if err != nil {
logger.WithError(err).Error("error getting snstopics")
return err
}
for _, resource := range resources.Items {
if resource.Status.StackID == msg.ParsedMessage["StackId"] {
name = resource.Name
namespace = resource.Namespace
}
}
}
if name != "" && namespace != "" {
if msg.ParsedMessage["ResourceStatus"] == "ROLLBACK_COMPLETE" {
err := deleteStack(config, name, namespace, msg.ParsedMessage["StackId"])
if err != nil {
return err
}
} else if msg.ParsedMessage["ResourceStatus"] == "DELETE_COMPLETE" {
err := updateStatus(config, name, namespace, msg.ParsedMessage["StackId"], msg.ParsedMessage["ResourceStatus"], msg.ParsedMessage["ResourceStatusReason"])
if err != nil {
return err
}
err = incrementRollbackCount(config, name, namespace)
if err != nil {
return err
}
} else {
err := updateStatus(config, name, namespace, msg.ParsedMessage["StackId"], msg.ParsedMessage["ResourceStatus"], msg.ParsedMessage["ResourceStatusReason"])
if err != nil {
return err
}
}
}
return nil
}
func (c *Controller) onAdd(obj interface{}) {
s := obj.(*awsV1alpha1.SNSTopic).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 snstopic '%s'", s.Name)
return
}
c.config.Logger.Infof("added snstopic '%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 *Controller) onUpdate(oldObj, newObj interface{}) {
oo := oldObj.(*awsV1alpha1.SNSTopic).DeepCopy()
no := newObj.(*awsV1alpha1.SNSTopic).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 snstopic '%s' with new params %+v and old %+v", no.Name, no, oo)
return
}
c.config.Logger.Infof("updated snstopic '%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 *Controller) onDelete(obj interface{}) {
s := obj.(*awsV1alpha1.SNSTopic).DeepCopy()
cft := New(c.config, s, c.topicARN)
err := cft.DeleteStack()
if err != nil {
c.config.Logger.WithError(err).Errorf("error deleting snstopic '%s'", s.Name)
return
}
c.config.Logger.Infof("deleted snstopic '%s'", s.Name)
}
func incrementRollbackCount(config *config.Config, name string, namespace string) error {
logger := config.Logger
clientSet, _ := awsclient.NewForConfig(config.RESTConfig)
resource, err := clientSet.SNSTopics(namespace).Get(name, metav1.GetOptions{})
if err != nil {
logger.WithError(err).Error("error getting snstopics")
return err
}
resourceCopy := resource.DeepCopy()
resourceCopy.Spec.RollbackCount = resourceCopy.Spec.RollbackCount + 1
_, err = clientSet.SNSTopics(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) error {
logger := config.Logger
clientSet, _ := awsclient.NewForConfig(config.RESTConfig)
resource, err := clientSet.SNSTopics(namespace).Get(name, metav1.GetOptions{})
if err != nil {
logger.WithError(err).Error("error getting snstopics")
return 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.TopicARN = outputs["TopicARN"]
}
_, err = clientSet.SNSTopics(namespace).Update(resourceCopy)
if err != nil {
logger.WithError(err).Error("error updating resource")
return err
}
if helpers.IsStackComplete(status, false) {
err = syncAdditionalResources(config, resourceCopy)
if err != nil {
logger.WithError(err).Info("error syncing resources")
}
}
return nil
}
func deleteStack(config *config.Config, name string, namespace string, stackID string) error {
logger := config.Logger
clientSet, _ := awsclient.NewForConfig(config.RESTConfig)
resource, err := clientSet.SNSTopics(namespace).Get(name, metav1.GetOptions{})
if err != nil {
logger.WithError(err).Error("error getting snstopics")
return err
}
cft := New(config, resource, "")
err = cft.DeleteStack()
if err != nil {
return err
}
err = cft.WaitUntilStackDeleted()
return err
}
func syncAdditionalResources(config *config.Config, s *awsV1alpha1.SNSTopic) (err error) {
clientSet, _ := awsclient.NewForConfig(config.RESTConfig)
resource, err := clientSet.SNSTopics(s.Namespace).Get(s.Name, metav1.GetOptions{})
if err != nil {
return err
}
resource = resource.DeepCopy()
_, err = clientSet.SNSTopics(s.Namespace).Update(resource)
if err != nil {
return err
}
return nil
}