forked from argoproj/argo-cd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.go
267 lines (236 loc) · 9.75 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
package controller
import (
"context"
"errors"
"fmt"
"time"
"github.com/argoproj/argo-cd/v2/util/glob"
"github.com/argoproj/argo-cd/v2/util/notification/k8s"
service "github.com/argoproj/argo-cd/v2/util/notification/argocd"
argocert "github.com/argoproj/argo-cd/v2/util/cert"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/argoproj/argo-cd/v2/util/notification/settings"
"github.com/argoproj/argo-cd/v2/pkg/apis/application"
"github.com/argoproj/notifications-engine/pkg/api"
"github.com/argoproj/notifications-engine/pkg/controller"
"github.com/argoproj/notifications-engine/pkg/services"
"github.com/argoproj/notifications-engine/pkg/subscriptions"
httputil "github.com/argoproj/notifications-engine/pkg/util/http"
log "github.com/sirupsen/logrus"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
)
const (
resyncPeriod = 60 * time.Second
)
var (
applications = schema.GroupVersionResource{Group: application.Group, Version: "v1alpha1", Resource: application.ApplicationPlural}
appProjects = schema.GroupVersionResource{Group: application.Group, Version: "v1alpha1", Resource: application.AppProjectPlural}
)
func newAppProjClient(client dynamic.Interface, namespace string) dynamic.ResourceInterface {
resClient := client.Resource(appProjects).Namespace(namespace)
return resClient
}
type NotificationController interface {
Run(ctx context.Context, processors int)
Init(ctx context.Context) error
}
func NewController(
k8sClient kubernetes.Interface,
client dynamic.Interface,
argocdService service.Service,
namespace string,
applicationNamespaces []string,
appLabelSelector string,
registry *controller.MetricsRegistry,
secretName string,
configMapName string,
selfServiceNotificationEnabled bool,
) *notificationController {
var appClient dynamic.ResourceInterface
namespaceableAppClient := client.Resource(applications)
appClient = namespaceableAppClient
if len(applicationNamespaces) == 0 {
appClient = namespaceableAppClient.Namespace(namespace)
}
appInformer := newInformer(appClient, namespace, applicationNamespaces, appLabelSelector)
appProjInformer := newInformer(newAppProjClient(client, namespace), namespace, []string{namespace}, "")
var notificationConfigNamespace string
if selfServiceNotificationEnabled {
notificationConfigNamespace = v1.NamespaceAll
} else {
notificationConfigNamespace = namespace
}
secretInformer := k8s.NewSecretInformer(k8sClient, notificationConfigNamespace, secretName)
configMapInformer := k8s.NewConfigMapInformer(k8sClient, notificationConfigNamespace, configMapName)
apiFactory := api.NewFactory(settings.GetFactorySettings(argocdService, secretName, configMapName, selfServiceNotificationEnabled), namespace, secretInformer, configMapInformer)
res := ¬ificationController{
secretInformer: secretInformer,
configMapInformer: configMapInformer,
appInformer: appInformer,
appProjInformer: appProjInformer,
apiFactory: apiFactory}
skipProcessingOpt := controller.WithSkipProcessing(func(obj v1.Object) (bool, string) {
app, ok := (obj).(*unstructured.Unstructured)
if !ok {
return false, ""
}
if checkAppNotInAdditionalNamespaces(app, namespace, applicationNamespaces) {
return true, "app is not in one of the application-namespaces, nor the notification controller namespace"
}
return !isAppSyncStatusRefreshed(app, log.WithField("app", obj.GetName())), "sync status out of date"
})
metricsRegistryOpt := controller.WithMetricsRegistry(registry)
alterDestinationsOpt := controller.WithAlterDestinations(res.alterDestinations)
if !selfServiceNotificationEnabled {
res.ctrl = controller.NewController(namespaceableAppClient, appInformer, apiFactory,
skipProcessingOpt,
metricsRegistryOpt,
alterDestinationsOpt)
} else {
res.ctrl = controller.NewControllerWithNamespaceSupport(namespaceableAppClient, appInformer, apiFactory,
skipProcessingOpt,
metricsRegistryOpt,
alterDestinationsOpt)
}
return res
}
// Check if app is not in the namespace where the controller is in, and also app is not in one of the applicationNamespaces
func checkAppNotInAdditionalNamespaces(app *unstructured.Unstructured, namespace string, applicationNamespaces []string) bool {
return namespace != app.GetNamespace() && !glob.MatchStringInList(applicationNamespaces, app.GetNamespace(), false)
}
func (c *notificationController) alterDestinations(obj v1.Object, destinations services.Destinations, cfg api.Config) services.Destinations {
app, ok := (obj).(*unstructured.Unstructured)
if !ok {
return destinations
}
if proj := getAppProj(app, c.appProjInformer); proj != nil {
destinations.Merge(subscriptions.NewAnnotations(proj.GetAnnotations()).GetDestinations(cfg.DefaultTriggers, cfg.ServiceDefaultTriggers))
destinations.Merge(settings.GetLegacyDestinations(proj.GetAnnotations(), cfg.DefaultTriggers, cfg.ServiceDefaultTriggers))
}
return destinations
}
func newInformer(resClient dynamic.ResourceInterface, controllerNamespace string, applicationNamespaces []string, selector string) cache.SharedIndexInformer {
informer := cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
// We are only interested in apps that exist in namespaces the
// user wants to be enabled.
options.LabelSelector = selector
appList, err := resClient.List(context.TODO(), options)
if err != nil {
return nil, fmt.Errorf("failed to list applications: %w", err)
}
newItems := []unstructured.Unstructured{}
for _, res := range appList.Items {
if controllerNamespace == res.GetNamespace() || glob.MatchStringInList(applicationNamespaces, res.GetNamespace(), false) {
newItems = append(newItems, res)
}
}
appList.Items = newItems
return appList, nil
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
options.LabelSelector = selector
return resClient.Watch(context.TODO(), options)
},
},
&unstructured.Unstructured{},
resyncPeriod,
cache.Indexers{
cache.NamespaceIndex: func(obj interface{}) ([]string, error) {
return cache.MetaNamespaceIndexFunc(obj)
},
},
)
return informer
}
type notificationController struct {
apiFactory api.Factory
ctrl controller.NotificationController
appInformer cache.SharedIndexInformer
appProjInformer cache.SharedIndexInformer
secretInformer cache.SharedIndexInformer
configMapInformer cache.SharedIndexInformer
}
func (c *notificationController) Init(ctx context.Context) error {
// resolve certificates using injected "argocd-tls-certs-cm" ConfigMap
httputil.SetCertResolver(argocert.GetCertificateForConnect)
go c.appInformer.Run(ctx.Done())
go c.appProjInformer.Run(ctx.Done())
go c.secretInformer.Run(ctx.Done())
go c.configMapInformer.Run(ctx.Done())
if !cache.WaitForCacheSync(ctx.Done(), c.appInformer.HasSynced, c.appProjInformer.HasSynced, c.secretInformer.HasSynced, c.configMapInformer.HasSynced) {
return errors.New("Timed out waiting for caches to sync")
}
return nil
}
func (c *notificationController) Run(ctx context.Context, processors int) {
c.ctrl.Run(processors, ctx.Done())
}
func getAppProj(app *unstructured.Unstructured, appProjInformer cache.SharedIndexInformer) *unstructured.Unstructured {
projName, ok, err := unstructured.NestedString(app.Object, "spec", "project")
if !ok || err != nil {
return nil
}
projObj, ok, err := appProjInformer.GetIndexer().GetByKey(fmt.Sprintf("%s/%s", app.GetNamespace(), projName))
if !ok || err != nil {
return nil
}
proj, ok := projObj.(*unstructured.Unstructured)
if !ok {
return nil
}
if proj.GetAnnotations() == nil {
proj.SetAnnotations(map[string]string{})
}
return proj
}
// Checks if the application SyncStatus has been refreshed by Argo CD after an operation has completed
func isAppSyncStatusRefreshed(app *unstructured.Unstructured, logEntry *log.Entry) bool {
_, ok, err := unstructured.NestedMap(app.Object, "status", "operationState")
if !ok || err != nil {
logEntry.Debug("No OperationState found, SyncStatus is assumed to be up-to-date")
return true
}
phase, ok, err := unstructured.NestedString(app.Object, "status", "operationState", "phase")
if !ok || err != nil {
logEntry.Debug("No OperationPhase found, SyncStatus is assumed to be up-to-date")
return true
}
switch phase {
case "Failed", "Error", "Succeeded":
finishedAtRaw, ok, err := unstructured.NestedString(app.Object, "status", "operationState", "finishedAt")
if !ok || err != nil {
logEntry.Debugf("No FinishedAt found for completed phase '%s', SyncStatus is assumed to be out-of-date", phase)
return false
}
finishedAt, err := time.Parse(time.RFC3339, finishedAtRaw)
if err != nil {
logEntry.Warnf("Failed to parse FinishedAt '%s'", finishedAtRaw)
return false
}
var reconciledAt, observedAt time.Time
reconciledAtRaw, ok, err := unstructured.NestedString(app.Object, "status", "reconciledAt")
if ok && err == nil {
reconciledAt, _ = time.Parse(time.RFC3339, reconciledAtRaw)
}
observedAtRaw, ok, err := unstructured.NestedString(app.Object, "status", "observedAt")
if ok && err == nil {
observedAt, _ = time.Parse(time.RFC3339, observedAtRaw)
}
if finishedAt.After(reconciledAt) && finishedAt.After(observedAt) {
logEntry.Debugf("SyncStatus out-of-date (FinishedAt=%v, ReconciledAt=%v, Observed=%v", finishedAt, reconciledAt, observedAt)
return false
}
logEntry.Debugf("SyncStatus up-to-date (FinishedAt=%v, ReconciledAt=%v, Observed=%v", finishedAt, reconciledAt, observedAt)
default:
logEntry.Debugf("Found phase '%s', SyncStatus is assumed to be up-to-date", phase)
}
return true
}