forked from tektoncd/triggers
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sink.go
260 lines (234 loc) · 9.09 KB
/
sink.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
/*
Copyright 2019 The Tekton Authors
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.
*/
package sink
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
triggersv1 "github.com/tektoncd/triggers/pkg/apis/triggers/v1alpha1"
triggersclientset "github.com/tektoncd/triggers/pkg/client/clientset/versioned"
"github.com/tektoncd/triggers/pkg/interceptors"
"github.com/tektoncd/triggers/pkg/interceptors/bitbucket"
"github.com/tektoncd/triggers/pkg/interceptors/cel"
"github.com/tektoncd/triggers/pkg/interceptors/github"
"github.com/tektoncd/triggers/pkg/interceptors/gitlab"
"github.com/tektoncd/triggers/pkg/interceptors/webhook"
"github.com/tektoncd/triggers/pkg/resources"
"github.com/tektoncd/triggers/pkg/template"
"go.uber.org/zap"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
discoveryclient "k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
)
// Sink defines the sink resource for processing incoming events for the
// EventListener.
type Sink struct {
KubeClientSet kubernetes.Interface
TriggersClient triggersclientset.Interface
DiscoveryClient discoveryclient.ServerResourcesInterface
DynamicClient dynamic.Interface
HTTPClient *http.Client
EventListenerName string
EventListenerNamespace string
Logger *zap.SugaredLogger
Auth AuthOverride
}
// Response defines the HTTP body that the Sink responds to events with.
type Response struct {
// EventListener is the name of the eventListener
EventListener string `json:"eventListener"`
// Namespace is the namespace that the eventListener is running in
Namespace string `json:"namespace,omitempty"`
// EventID is a uniqueID that gets assigned to each incoming request
EventID string `json:"eventID,omitempty"`
}
// HandleEvent processes an incoming HTTP event for the event listener.
func (r Sink) HandleEvent(response http.ResponseWriter, request *http.Request) {
el, err := r.TriggersClient.TriggersV1alpha1().EventListeners(r.EventListenerNamespace).Get(r.EventListenerName, metav1.GetOptions{})
if err != nil {
r.Logger.Fatalf("Error getting EventListener %s in Namespace %s: %s", r.EventListenerName, r.EventListenerNamespace, err)
response.WriteHeader(http.StatusInternalServerError)
return
}
event, err := ioutil.ReadAll(request.Body)
if err != nil {
r.Logger.Errorf("Error reading event body: %s", err)
response.WriteHeader(http.StatusInternalServerError)
return
}
eventID := template.UID()
eventLog := r.Logger.With(zap.String(triggersv1.EventIDLabelKey, eventID))
eventLog.Debugf("EventListener: %s in Namespace: %s handling event (EventID: %s) with payload: %s and header: %v",
r.EventListenerName, r.EventListenerNamespace, eventID, string(event), request.Header)
result := make(chan int, 10)
// Execute each Trigger
for _, t := range el.Spec.Triggers {
go func(t triggersv1.EventListenerTrigger) {
localRequest := request.Clone(request.Context())
if err := r.processTrigger(&t, localRequest, event, eventID, eventLog); err != nil {
if kerrors.IsUnauthorized(err) {
result <- http.StatusUnauthorized
return
}
if kerrors.IsForbidden(err) {
result <- http.StatusForbidden
}
result <- http.StatusAccepted
return
}
result <- http.StatusCreated
}(t)
}
//The eventlistener waits until all the trigger executions (up-to the creation of the resources) and
//only when at least one of the execution completed successfully, it returns response code 201(Created) otherwise it returns 202 (Accepted).
code := http.StatusAccepted
for i := 0; i < len(el.Spec.Triggers); i++ {
thiscode := <-result
// current take - if someone is doing unauthorized stuff, we abort immediately;
// unauthorized should be the final status code vs. the less than comparison
// below around accepted vs. created
if thiscode == http.StatusUnauthorized || thiscode == http.StatusForbidden {
code = thiscode
break
}
if thiscode < code {
code = thiscode
}
}
response.WriteHeader(code)
response.Header().Set("Content-Type", "application/json")
body := Response{
EventListener: r.EventListenerName,
Namespace: r.EventListenerNamespace,
EventID: eventID,
}
if err := json.NewEncoder(response).Encode(body); err != nil {
eventLog.Errorf("failed to write back sink response: %w", err)
}
}
func (r Sink) processTrigger(t *triggersv1.EventListenerTrigger, request *http.Request, event []byte, eventID string, eventLog *zap.SugaredLogger) error {
if t == nil {
return errors.New("EventListenerTrigger not defined")
}
log := eventLog.With(zap.String(triggersv1.TriggerLabelKey, t.Name))
finalPayload, header, err := r.executeInterceptors(t, request, event, log)
if err != nil {
log.Error(err)
return err
}
rt, err := template.ResolveTrigger(*t,
r.TriggersClient.TriggersV1alpha1().TriggerBindings(r.EventListenerNamespace).Get,
r.TriggersClient.TriggersV1alpha1().ClusterTriggerBindings().Get,
r.TriggersClient.TriggersV1alpha1().TriggerTemplates(r.EventListenerNamespace).Get)
if err != nil {
log.Error(err)
return err
}
params, err := template.ResolveParams(rt, finalPayload, header)
if err != nil {
log.Error(err)
return err
}
log.Infof("ResolvedParams : %+v", params)
resources := template.ResolveResources(rt.TriggerTemplate, params)
token, err := r.retrieveAuthToken(t.ServiceAccount, eventLog)
if err != nil {
log.Error(err)
return err
}
if err := r.createResources(token, resources, t.Name, eventID, log); err != nil {
log.Error(err)
return err
}
return nil
}
func (r Sink) executeInterceptors(t *triggersv1.EventListenerTrigger, in *http.Request, event []byte, log *zap.SugaredLogger) ([]byte, http.Header, error) {
if len(t.Interceptors) == 0 {
return event, in.Header, nil
}
// The request body to the first interceptor in the chain should be the received event body.
request := &http.Request{
Method: http.MethodPost,
Header: in.Header,
URL: in.URL,
Body: ioutil.NopCloser(bytes.NewBuffer(event)),
}
// We create a cache against each request, so whenever we make network calls like
// fetching kubernetes secrets, we can do so only once per request.
request = interceptors.WithCache(request)
var resp *http.Response
for _, i := range t.Interceptors {
var interceptor interceptors.Interceptor
switch {
case i.Webhook != nil:
interceptor = webhook.NewInterceptor(i.Webhook, r.HTTPClient, r.EventListenerNamespace, log)
case i.GitHub != nil:
interceptor = github.NewInterceptor(i.GitHub, r.KubeClientSet, r.EventListenerNamespace, log)
case i.GitLab != nil:
interceptor = gitlab.NewInterceptor(i.GitLab, r.KubeClientSet, r.EventListenerNamespace, log)
case i.CEL != nil:
interceptor = cel.NewInterceptor(i.CEL, r.KubeClientSet, r.EventListenerNamespace, log)
case i.Bitbucket != nil:
interceptor = bitbucket.NewInterceptor(i.Bitbucket, r.KubeClientSet, r.EventListenerNamespace, log)
default:
return nil, nil, fmt.Errorf("unknown interceptor type: %v", i)
}
var err error
resp, err = interceptor.ExecuteTrigger(request)
if err != nil {
return nil, nil, err
}
// Set the next request to be the output of the last response to enable
// request chaining.
request = &http.Request{
Method: http.MethodPost,
Header: resp.Header,
URL: in.URL,
Body: ioutil.NopCloser(resp.Body),
}
}
payload, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("error reading final response body: %w", err)
}
defer resp.Body.Close()
return payload, resp.Header, nil
}
func (r Sink) createResources(token string, res []json.RawMessage, triggerName, eventID string, log *zap.SugaredLogger) error {
discoveryClient := r.DiscoveryClient
dynamicClient := r.DynamicClient
var err error
if len(token) > 0 {
// So at start up the discovery and dynamic clients are created using the in cluster config
// of this pod (i.e. using the credentials of the serviceaccount associated with the EventListener)
// However, we also have a ServiceAccount/Secret/SecretKey reference with each EventListenerTrigger to allow
// for more fine grained authorization control around the resources we create below.
discoveryClient, dynamicClient, err = r.Auth.OverrideAuthentication(token, log, r.DiscoveryClient, r.DynamicClient)
if err != nil {
log.Errorf("problem cloning rest config: %#v", err)
return err
}
}
for _, rr := range res {
if err := resources.Create(r.Logger, rr, triggerName, eventID, r.EventListenerName, r.EventListenerNamespace, discoveryClient, dynamicClient); err != nil {
log.Errorf("problem creating obj: %#v", err)
return err
}
}
return nil
}