/
siddhicontroller.go
505 lines (466 loc) · 16 KB
/
siddhicontroller.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
/*
* Copyright (c) 2019 WSO2 Inc. (http:www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.
*/
package siddhicontroller
import (
"context"
"os"
"strconv"
"strings"
logr "github.com/go-logr/logr"
siddhiv1alpha2 "github.com/siddhi-io/siddhi-operator/pkg/apis/siddhi/v1alpha2"
artifact "github.com/siddhi-io/siddhi-operator/pkg/controller/siddhiprocess/artifact"
deploymanager "github.com/siddhi-io/siddhi-operator/pkg/controller/siddhiprocess/deploymanager"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
// SiddhiController control all deployments of the SiddhiProcess
type SiddhiController struct {
SiddhiProcess *siddhiv1alpha2.SiddhiProcess
EventRecorder record.EventRecorder
Logger logr.Logger
KubeClient artifact.KubeClient
Image deploymanager.Image
AutoCreateIngress bool
TLS string
}
// ConfigMapListner holds the change details of a config map
type ConfigMapListner struct {
SiddhiProcess string `json:"siddhiProcess"`
Changed bool `json:"changed"`
}
// UpdateErrorStatus update the status of the CR object and send events to the SiddhiProcess object using EventRecorder object
// These status can be Warning, Error
func (sc *SiddhiController) UpdateErrorStatus(
reason string,
er error,
) {
st := getStatus(ERROR)
s := sc.SiddhiProcess
sc.SiddhiProcess.Status.Status = st
sc.EventRecorder.Event(sc.SiddhiProcess, getStatus(WARNING), reason, er.Error())
sc.Logger.Error(er, er.Error())
err := sc.KubeClient.Client.Status().Update(context.TODO(), sc.SiddhiProcess)
if err != nil {
sc.SiddhiProcess = s
}
}
// UpdateWarningStatus update the status of the CR object and send events to the SiddhiProcess object using EventRecorder object
// These status can be Warning, Error
func (sc *SiddhiController) UpdateWarningStatus(
reason string,
er error,
) {
st := getStatus(WARNING)
s := sc.SiddhiProcess
sc.SiddhiProcess.Status.Status = st
sc.EventRecorder.Event(sc.SiddhiProcess, getStatus(WARNING), reason, er.Error())
sc.Logger.Info(er.Error())
err := sc.KubeClient.Client.Status().Update(context.TODO(), sc.SiddhiProcess)
if err != nil {
sc.SiddhiProcess = s
}
}
// UpdateRunningStatus send events to the SiddhiProcess object using EventRecorder object
func (sc *SiddhiController) UpdateRunningStatus(
reason string,
message string,
) {
s := sc.SiddhiProcess
if reason != "" && message != "" {
sc.EventRecorder.Event(sc.SiddhiProcess, getStatus(NORMAL), reason, message)
sc.Logger.Info(message)
}
err := sc.KubeClient.Client.Status().Update(context.TODO(), sc.SiddhiProcess)
if err != nil {
sc.SiddhiProcess = s
}
}
// UpdatePartialAppStatus update the status of the CR object to Pending status
func (sc *SiddhiController) UpdatePartialAppStatus(applications []deploymanager.Application) {
s := sc.SiddhiProcess
partialApps := []siddhiv1alpha2.PartialApp{}
for _, application := range applications {
apps := []string{}
for _, app := range application.Apps {
apps = append(apps, app)
}
partialApp := siddhiv1alpha2.PartialApp{
DeploymentName: application.Name,
Apps: apps,
}
partialApps = append(partialApps, partialApp)
}
sc.SiddhiProcess.Status.PartialApps = partialApps
err := sc.KubeClient.Client.Status().Update(context.TODO(), sc.SiddhiProcess)
if err != nil {
sc.SiddhiProcess = s
}
}
// UpdatePendingStatus update the status of the CR object to Pending status
func (sc *SiddhiController) UpdatePendingStatus() {
st := getStatus(PENDING)
s := sc.SiddhiProcess
sc.SiddhiProcess.Status.Status = st
err := sc.KubeClient.Client.Status().Update(context.TODO(), sc.SiddhiProcess)
if err != nil {
sc.SiddhiProcess = s
}
}
// UpdateNotReadytatus update the status of the CR object to Not Ready status
func (sc *SiddhiController) UpdateNotReadytatus() {
st := getStatus(NOTREADY)
s := sc.SiddhiProcess
sc.SiddhiProcess.Status.Status = st
err := sc.KubeClient.Client.Status().Update(context.TODO(), sc.SiddhiProcess)
if err != nil {
sc.SiddhiProcess = s
}
}
// UpdateReadyStatus update the status of the CR object to Ready status
func (sc *SiddhiController) UpdateReadyStatus() {
st := getStatus(READY)
s := sc.SiddhiProcess
sc.SiddhiProcess.Status.Status = st
err := sc.KubeClient.Client.Status().Update(context.TODO(), sc.SiddhiProcess)
if err != nil {
sc.SiddhiProcess = s
}
}
// UpdateReadyDeployments update ready attribute of the CR object
// Ready attribute contains the number of deployments are complete and running out of requested deployments
func (sc *SiddhiController) UpdateReadyDeployments(available int, need int) {
s := sc.SiddhiProcess
s.Status.Ready = strconv.Itoa(available) + "/" + strconv.Itoa(need)
err := sc.KubeClient.Client.Status().Update(context.TODO(), sc.SiddhiProcess)
if err != nil {
sc.SiddhiProcess = s
}
}
// CreateArtifacts simply create all the k8s artifacts which needed in the siddhiApps list.
// This function creates deployment, service, and ingress. If ingress was available the it will update the ingress.
func (sc *SiddhiController) CreateArtifacts(applications []deploymanager.Application) {
needDep := 0
availableDep := 0
eventType := getEventType(
sc.SiddhiProcess.Status.CurrentVersion,
sc.SiddhiProcess.Status.PreviousVersion,
)
sc.UpdatePartialAppStatus(applications)
for _, application := range applications {
if eventType == controllerutil.OperationResultCreated ||
eventType == controllerutil.OperationResultUpdated {
deployManeger := deploymanager.DeployManager{
Application: application,
KubeClient: sc.KubeClient,
Image: sc.Image,
SiddhiProcess: sc.SiddhiProcess,
}
needDep++
operationResult, err := deployManeger.Deploy()
if err != nil {
sc.UpdateErrorStatus("AppDeploymentError", err)
continue
}
if eventType == controllerutil.OperationResultCreated &&
operationResult == controllerutil.OperationResultCreated {
sc.UpdateRunningStatus(
"DeploymentCreated",
(application.Name + " deployment created successfully"),
)
} else if eventType == controllerutil.OperationResultUpdated &&
operationResult == controllerutil.OperationResultUpdated {
sc.UpdateRunningStatus(
"DeploymentUpdated",
(application.Name + " deployment updated successfully"),
)
}
availableDep++
if application.ServiceEnabled {
operationResult, err = sc.KubeClient.CreateOrUpdateService(
application.Name,
sc.SiddhiProcess.Namespace,
application.ContainerPorts,
deployManeger.Labels,
sc.SiddhiProcess,
)
if err != nil {
sc.UpdateErrorStatus("ServiceCreationError", err)
continue
}
if eventType == controllerutil.OperationResultCreated &&
operationResult == controllerutil.OperationResultCreated {
sc.UpdateRunningStatus(
"ServiceCreated",
(application.Name + " service created successfully"),
)
} else if eventType == controllerutil.OperationResultUpdated &&
operationResult == controllerutil.OperationResultUpdated {
sc.UpdateRunningStatus(
"ServiceUpdated",
(application.Name + " service updated successfully"),
)
}
if sc.AutoCreateIngress {
operationResult, err = sc.KubeClient.CreateOrUpdateIngress(
sc.SiddhiProcess.Namespace,
application.Name,
sc.TLS,
application.ContainerPorts,
)
if err != nil {
sc.UpdateErrorStatus("IngressCreationError", err)
continue
}
if eventType == controllerutil.OperationResultCreated &&
operationResult == controllerutil.OperationResultCreated {
sc.Logger.Info("Ingress created", "Ingress.Name", artifact.IngressName)
} else if eventType == controllerutil.OperationResultUpdated &&
operationResult == controllerutil.OperationResultUpdated {
sc.Logger.Info("Ingress changed", "Ingress.Name", artifact.IngressName)
}
}
}
}
}
sc.SyncVersion()
if eventType == controllerutil.OperationResultCreated || eventType == controllerutil.OperationResultUpdated {
sc.UpdateReadyDeployments(0, needDep)
}
return
}
// CheckDeployments function check the availability of deployments and the replications of the deployments.
func (sc *SiddhiController) CheckDeployments(applications []deploymanager.Application) {
for _, application := range applications {
deployment := &appsv1.Deployment{}
err := sc.KubeClient.Client.Get(
context.TODO(),
types.NamespacedName{
Name: strings.ToLower(application.Name),
Namespace: sc.SiddhiProcess.Namespace,
},
deployment,
)
if err == nil && *deployment.Spec.Replicas != application.Replicas {
deployment.Spec.Replicas = &application.Replicas
err = sc.KubeClient.Client.Update(context.TODO(), deployment)
if err != nil {
sc.UpdateErrorStatus("DeploymentUpdationError", err)
continue
}
}
}
}
// CheckAvailableDeployments function check the availability of deployments and the replications of the deployments.
func (sc *SiddhiController) CheckAvailableDeployments(applications []deploymanager.Application) (terminate bool) {
availableDeployments := 0
needDeployments := 0
isStatelessReady := true
needStatefulDeployments := 0
availableStatefuleDeployments := 0
needStatelessDeployments := 0
availableStatelesseDeployments := 0
for _, application := range applications {
deployment := &appsv1.Deployment{}
err := sc.KubeClient.Client.Get(
context.TODO(),
types.NamespacedName{
Name: strings.ToLower(application.Name),
Namespace: sc.SiddhiProcess.Namespace,
},
deployment,
)
needDeployments += int(application.Replicas)
if err == nil && &deployment.Status.AvailableReplicas != nil {
availableDeployments += int(deployment.Status.AvailableReplicas)
}
if application.PersistenceEnabled {
needStatefulDeployments += int(application.Replicas)
if err == nil && &deployment.Status.AvailableReplicas != nil {
availableStatefuleDeployments += int(deployment.Status.AvailableReplicas)
}
} else {
needStatelessDeployments += int(application.Replicas)
if err == nil && &deployment.Status.AvailableReplicas != nil {
availableStatelesseDeployments += int(deployment.Status.AvailableReplicas)
if int(deployment.Status.AvailableReplicas) == 0 {
isStatelessReady = false
}
}
}
}
sc.UpdateReadyDeployments(availableDeployments, needDeployments)
if needDeployments == availableDeployments {
terminate = true
sc.UpdateReadyStatus()
return
} else if isStatelessReady && (needStatefulDeployments == availableStatefuleDeployments) {
sc.UpdateReadyStatus()
} else {
sc.UpdateNotReadytatus()
}
terminate = false
return
}
// SyncVersion synchronize the siddhi process internal version number
// this simply assing Status.CurrentVersion value to the Status.PreviousVersion and update the siddhi process
// this funtionality used for version controlling inside a siddhi process
func (sc *SiddhiController) SyncVersion() {
sc.SiddhiProcess.Status.PreviousVersion = sc.SiddhiProcess.Status.CurrentVersion
_ = sc.KubeClient.Client.Status().Update(context.TODO(), sc.SiddhiProcess)
}
// UpgradeVersion upgrade the siddhi process internal version number
func (sc *SiddhiController) UpgradeVersion() {
sc.SiddhiProcess.Status.CurrentVersion++
_ = sc.KubeClient.Client.Status().Update(context.TODO(), sc.SiddhiProcess)
}
// CleanArtifacts function delete the k8s artifacts that are not relavant when user changes the existing SiddhiProcess
// When user change stateful siddhi process to stateless the unwanted artifacts will be deleted by this function
func (sc *SiddhiController) CleanArtifacts(
oldApps []deploymanager.Application,
newApps []deploymanager.Application,
) (err error) {
oldAppsLen := len(oldApps)
newAppsLen := len(newApps)
if newAppsLen < oldAppsLen {
for i := newAppsLen; i < oldAppsLen; i++ {
artifactName := sc.SiddhiProcess.Name + "-" + strconv.Itoa(i)
err = sc.KubeClient.DeleteDeployment(artifactName, sc.SiddhiProcess.Namespace)
if err != nil {
return
}
sc.UpdateRunningStatus(
"DeploymentDeleted",
(artifactName + " deployment deleted successfully"),
)
err = sc.KubeClient.DeleteService(artifactName, sc.SiddhiProcess.Namespace)
if err != nil {
return
}
sc.UpdateRunningStatus(
"ServiceDeleted",
(artifactName + " service deleted successfully"),
)
pvcName := artifactName + deploymanager.PVCExtension
err = sc.KubeClient.DeletePVC(pvcName, sc.SiddhiProcess.Namespace)
if err != nil {
return
}
cmName := artifactName + strconv.Itoa(int(sc.SiddhiProcess.Status.PreviousVersion))
err = sc.KubeClient.DeleteConfigMap(cmName, sc.SiddhiProcess.Namespace)
if err != nil {
return
}
}
}
return
}
func getEventType(currentVersion int64, previousVersion int64) (eventType controllerutil.OperationResult) {
if currentVersion == 0 {
eventType = controllerutil.OperationResultCreated
} else {
if currentVersion > previousVersion {
eventType = controllerutil.OperationResultUpdated
} else {
eventType = controllerutil.OperationResultNone
}
}
return
}
// UpdateDefaultConfigs updates the default configs of Image, TLS, and ingress creation
func (sc *SiddhiController) UpdateDefaultConfigs() {
cmName := OperatorCMName
env := os.Getenv("OPERATOR_CONFIGMAP")
if env != "" {
cmName = env
}
sc.Image.Home = SiddhiHome
sc.Image.Name = SiddhiImage
sc.Image.Profile = SiddhiProfile
sc.AutoCreateIngress = AutoCreateIngress
configMap := &corev1.ConfigMap{}
err := sc.KubeClient.Client.Get(
context.TODO(),
types.NamespacedName{Name: cmName, Namespace: sc.SiddhiProcess.Namespace},
configMap,
)
if err == nil {
if v, ok := configMap.Data["siddhiHome"]; ok {
sc.Image.Home = v
}
if v, ok := configMap.Data["siddhiImage"]; ok {
sc.Image.Name = v
}
if v, ok := configMap.Data["siddhiImageSecret"]; ok {
sc.Image.Secret = v
}
if v, ok := configMap.Data["siddhiProfile"]; ok {
sc.Image.Profile = v
}
if v, ok := configMap.Data["autoIngressCreation"]; ok {
if v == "true" {
sc.AutoCreateIngress = true
} else {
sc.AutoCreateIngress = false
}
}
if v, ok := configMap.Data["ingressTLS"]; ok {
sc.TLS = v
}
}
if sc.SiddhiProcess.Spec.Container.Image != "" {
sc.Image.Name = sc.SiddhiProcess.Spec.Container.Image
}
if sc.SiddhiProcess.Spec.ImagePullSecret != "" {
sc.Image.Secret = sc.SiddhiProcess.Spec.ImagePullSecret
}
}
// GetDeploymentCount returns the deployment count to a given set of applications
func (sc *SiddhiController) GetDeploymentCount(applications []deploymanager.Application) (count int) {
count = 0
isDeployExists := false
for _, application := range applications {
_, isDeployExists = sc.KubeClient.GetDeployment(application.Name, sc.SiddhiProcess.Namespace)
if isDeployExists {
count = count + 1
}
}
return
}
// SetDefaultPendingState set the default state of a SiddhiProcess object to Pending
func (sc *SiddhiController) SetDefaultPendingState() {
eventType := getEventType(
sc.SiddhiProcess.Status.CurrentVersion,
sc.SiddhiProcess.Status.PreviousVersion,
)
if eventType == controllerutil.OperationResultCreated && sc.SiddhiProcess.Status.Status == "" {
sc.UpdatePendingStatus()
}
}
// SetNotReadyState set the state of a SiddhiProcess object to Updating
func (sc *SiddhiController) SetNotReadyState() {
eventType := getEventType(
sc.SiddhiProcess.Status.CurrentVersion,
sc.SiddhiProcess.Status.PreviousVersion,
)
if eventType == controllerutil.OperationResultUpdated {
sc.UpdateNotReadytatus()
}
}