-
Notifications
You must be signed in to change notification settings - Fork 718
/
custom-trigger.go
232 lines (192 loc) · 7.29 KB
/
custom-trigger.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
/*
Copyright 2020 BlackRock, Inc.
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 customtrigger
import (
"context"
"encoding/json"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials"
"k8s.io/apimachinery/pkg/util/wait"
"github.com/argoproj/argo-events/common"
"github.com/argoproj/argo-events/common/logging"
apicommon "github.com/argoproj/argo-events/pkg/apis/common"
"github.com/argoproj/argo-events/pkg/apis/sensor/v1alpha1"
"github.com/argoproj/argo-events/sensors/triggers"
)
// CustomTrigger implements Trigger interface for custom trigger resource
type CustomTrigger struct {
// Sensor object
Sensor *v1alpha1.Sensor
// Trigger definition
Trigger *v1alpha1.Trigger
// logger to log stuff
Logger *zap.SugaredLogger
// triggerClient is the gRPC client for the custom trigger server
triggerClient triggers.TriggerClient
}
// NewCustomTrigger returns a new custom trigger
func NewCustomTrigger(sensor *v1alpha1.Sensor, trigger *v1alpha1.Trigger, logger *zap.SugaredLogger, customTriggerClients map[string]*grpc.ClientConn) (*CustomTrigger, error) {
customTrigger := &CustomTrigger{
Sensor: sensor,
Trigger: trigger,
Logger: logger.With(logging.LabelTriggerType, apicommon.CustomTrigger),
}
ct := trigger.Template.CustomTrigger
if conn, ok := customTriggerClients[trigger.Template.Name]; ok {
if conn.GetState() == connectivity.Ready {
logger.Info("trigger client connection is ready...")
customTrigger.triggerClient = triggers.NewTriggerClient(conn)
return customTrigger, nil
}
logger.Info("trigger client connection is closed, creating new one...")
delete(customTriggerClients, trigger.Template.Name)
}
logger.Infow("instantiating trigger client...", zap.Any("server-url", ct.ServerURL))
opt := []grpc.DialOption{
grpc.WithBlock(),
grpc.WithInsecure(),
}
if ct.Secure {
var certFilePath string
var err error
switch {
case ct.CertSecret != nil:
certFilePath, err = common.GetSecretVolumePath(ct.CertSecret)
if err != nil {
return nil, err
}
case ct.DeprecatedCertFilePath != "":
// DEPRECATED
certFilePath = ct.DeprecatedCertFilePath
default:
return nil, errors.New("invalid config, CERT secret not defined")
}
creds, err := credentials.NewClientTLSFromFile(certFilePath, ct.ServerNameOverride)
if err != nil {
return nil, err
}
opt = append(opt, grpc.WithTransportCredentials(creds))
}
conn, err := grpc.Dial(
ct.ServerURL,
opt...,
)
if err != nil {
return nil, err
}
backoff, err := common.Convert2WaitBackoff(&common.DefaultBackoff)
if err != nil {
return nil, err
}
if err = wait.ExponentialBackoff(*backoff, func() (done bool, err error) {
if conn.GetState() == connectivity.Ready {
return true, nil
}
return false, nil
}); err != nil {
return nil, err
}
customTrigger.triggerClient = triggers.NewTriggerClient(conn)
customTriggerClients[trigger.Template.Name] = conn
logger.Info("successfully setup the trigger client...")
return customTrigger, nil
}
// GetTriggerType returns the type of the trigger
func (ct *CustomTrigger) GetTriggerType() apicommon.TriggerType {
return apicommon.CustomTrigger
}
// FetchResource fetches the trigger resource from external source
func (ct *CustomTrigger) FetchResource(ctx context.Context) (interface{}, error) {
specBody, err := yaml.Marshal(ct.Trigger.Template.CustomTrigger.Spec)
if err != nil {
return nil, errors.Wrap(err, "failed to parse the custom trigger spec body")
}
ct.Logger.Debugw("trigger spec body", zap.Any("spec", string(specBody)))
resource, err := ct.triggerClient.FetchResource(context.Background(), &triggers.FetchResourceRequest{
Resource: specBody,
})
if err != nil {
return nil, errors.Wrapf(err, "failed to fetch the custom trigger resource for %s", ct.Trigger.Template.Name)
}
ct.Logger.Debugw("fetched resource", zap.Any("resource", string(resource.Resource)))
return resource.Resource, nil
}
// ApplyResourceParameters applies parameters to the trigger resource
func (ct *CustomTrigger) ApplyResourceParameters(events map[string]*v1alpha1.Event, resource interface{}) (interface{}, error) {
obj, ok := resource.([]byte)
if !ok {
return nil, errors.New("failed to interpret the trigger resource for resource parameters application")
}
parameters := ct.Trigger.Template.CustomTrigger.Parameters
if len(parameters) > 0 {
// only JSON formatted resource body is eligible for parameters
var temp map[string]interface{}
if err := json.Unmarshal(obj, &temp); err != nil {
return nil, errors.Wrapf(err, "fetched resource body is not valid JSON for trigger %s", ct.Trigger.Template.Name)
}
result, err := triggers.ApplyParams(obj, ct.Trigger.Template.CustomTrigger.Parameters, events)
if err != nil {
return nil, errors.Wrapf(err, "failed to apply the parameters to the custom trigger resource for %s", ct.Trigger.Template.Name)
}
ct.Logger.Debugw("resource after parameterization", zap.Any("resource", string(result)))
return result, nil
}
return resource, nil
}
// Execute executes the trigger
func (ct *CustomTrigger) Execute(ctx context.Context, events map[string]*v1alpha1.Event, resource interface{}) (interface{}, error) {
obj, ok := resource.([]byte)
if !ok {
return nil, errors.New("failed to interpret the trigger resource for the execution")
}
ct.Logger.Debugw("resource to execute", zap.Any("resource", string(obj)))
trigger := ct.Trigger.Template.CustomTrigger
var payload []byte
var err error
if trigger.Payload != nil {
payload, err = triggers.ConstructPayload(events, trigger.Payload)
if err != nil {
return nil, err
}
ct.Logger.Debugw("payload for the trigger execution", zap.Any("payload", string(payload)))
}
result, err := ct.triggerClient.Execute(context.Background(), &triggers.ExecuteRequest{
Resource: obj,
Payload: payload,
})
if err != nil {
return nil, errors.Wrapf(err, "failed to execute the custom trigger resource for %s", ct.Trigger.Template.Name)
}
ct.Logger.Debugw("trigger execution response", zap.Any("response", string(result.Response)))
return result.Response, nil
}
// ApplyPolicy applies the policy on the trigger
func (ct *CustomTrigger) ApplyPolicy(ctx context.Context, resource interface{}) error {
obj, ok := resource.([]byte)
if !ok {
return errors.New("failed to interpret the trigger resource for the policy application")
}
ct.Logger.Debugw("resource to apply policy on", zap.Any("resource", string(obj)))
result, err := ct.triggerClient.ApplyPolicy(ctx, &triggers.ApplyPolicyRequest{
Request: obj,
})
if err != nil {
return errors.Wrapf(err, "failed to apply the policy for the custom trigger resource for %s", ct.Trigger.Template.Name)
}
ct.Logger.Infow("policy application result", zap.Any("success", result.Success), zap.Any("message", result.Message))
return err
}