-
Notifications
You must be signed in to change notification settings - Fork 729
/
http.go
207 lines (174 loc) · 6.26 KB
/
http.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
/*
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 http
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"io/ioutil"
"net/http"
"time"
"github.com/argoproj/argo-events/common"
"github.com/argoproj/argo-events/pkg/apis/sensor/v1alpha1"
"github.com/argoproj/argo-events/sensors/policy"
"github.com/argoproj/argo-events/sensors/triggers"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"k8s.io/client-go/kubernetes"
)
// HTTPTrigger describes the trigger to invoke HTTP request
type HTTPTrigger struct {
// Client is http client.
Client *http.Client
// K8sClient is the Kubernetes client
K8sClient kubernetes.Interface
// Sensor object
Sensor *v1alpha1.Sensor
// Trigger reference
Trigger *v1alpha1.Trigger
// Logger to log stuff
Logger *logrus.Logger
}
// NewHTTPTrigger returns a new HTTP trigger
func NewHTTPTrigger(httpClients map[string]*http.Client, k8sCLient kubernetes.Interface, sensor *v1alpha1.Sensor, trigger *v1alpha1.Trigger, logger *logrus.Logger) (*HTTPTrigger, error) {
httptrigger := trigger.Template.HTTP
client, ok := httpClients[trigger.Template.Name]
if !ok {
client = &http.Client{}
if httptrigger.TLS != nil {
caCert, err := ioutil.ReadFile(httptrigger.TLS.CACertPath)
if err != nil {
return nil, errors.Wrapf(err, "failed to read ca cert file %s", httptrigger.TLS.CACertPath)
}
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(caCert)
clientCert, err := tls.LoadX509KeyPair(httptrigger.TLS.ClientCertPath, httptrigger.TLS.ClientKeyPath)
if err != nil {
return nil, errors.Wrapf(err, "failed to load client cert key pair %s", httptrigger.TLS.CACertPath)
}
tlsConfig := tls.Config{
RootCAs: pool,
Certificates: []tls.Certificate{clientCert},
}
client.Transport = &http.Transport{
TLSClientConfig: &tlsConfig,
}
}
timeout := time.Second * 60
if httptrigger.Timeout > 0 {
timeout = time.Duration(httptrigger.Timeout) * time.Second
}
client.Timeout = timeout
httpClients[trigger.Template.Name] = client
}
return &HTTPTrigger{
Client: client,
K8sClient: k8sCLient,
Sensor: sensor,
Trigger: trigger,
Logger: logger,
}, nil
}
// FetchResource fetches the trigger. As the HTTP trigger simply executes a http request, there
// is no need to fetch any resource from external source
func (t *HTTPTrigger) FetchResource() (interface{}, error) {
if t.Trigger.Template.HTTP.Method == "" {
t.Trigger.Template.HTTP.Method = http.MethodPost
}
return t.Trigger.Template.HTTP, nil
}
// ApplyResourceParameters applies parameters to the trigger resource
func (t *HTTPTrigger) ApplyResourceParameters(sensor *v1alpha1.Sensor, resource interface{}) (interface{}, error) {
fetchedResource, ok := resource.(*v1alpha1.HTTPTrigger)
if !ok {
return nil, errors.New("failed to interpret the fetched trigger resource")
}
resourceBytes, err := json.Marshal(fetchedResource)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal the http trigger resource")
}
parameters := fetchedResource.Parameters
if parameters != nil {
updatedResourceBytes, err := triggers.ApplyParams(resourceBytes, parameters, triggers.ExtractEvents(sensor, parameters))
if err != nil {
return nil, err
}
var ht *v1alpha1.HTTPTrigger
if err := json.Unmarshal(updatedResourceBytes, &ht); err != nil {
return nil, errors.Wrap(err, "failed to unmarshal the updated http trigger resource after applying resource parameters")
}
return ht, nil
}
return resource, nil
}
// Execute executes the trigger
func (t *HTTPTrigger) Execute(resource interface{}) (interface{}, error) {
var payload []byte
var err error
trigger, ok := resource.(*v1alpha1.HTTPTrigger)
if !ok {
return nil, errors.New("failed to interpret the trigger resource")
}
if (trigger.Method == http.MethodPost || trigger.Method == http.MethodPatch || trigger.Method == http.MethodPut) && trigger.Payload == nil {
t.Logger.WithField("url", trigger.URL).Warnln("payload parameters are not specified. request payload will be an empty string")
}
if trigger.Payload != nil {
payload, err = triggers.ConstructPayload(t.Sensor, trigger.Payload)
if err != nil {
return nil, err
}
}
request, err := http.NewRequest(trigger.Method, trigger.URL, bytes.NewReader(payload))
if err != nil {
return nil, errors.Wrapf(err, "failed to construct request for %s", trigger.URL)
}
if trigger.Headers != nil {
request.Header = trigger.Headers
}
basicAuth := trigger.BasicAuth
if basicAuth != nil {
username := ""
password := ""
if basicAuth.Namespace == "" {
basicAuth.Namespace = t.Sensor.Namespace
}
if basicAuth.Username != nil {
username, err = common.GetSecretValue(t.K8sClient, basicAuth.Namespace, basicAuth.Username)
if err != nil {
return nil, errors.Wrapf(err, "failed to retrieve the username from secret %s and namespace %s", basicAuth.Username.Name, basicAuth.Namespace)
}
}
if basicAuth.Password != nil {
password, err = common.GetSecretValue(t.K8sClient, basicAuth.Namespace, basicAuth.Password)
if err != nil {
return nil, errors.Wrapf(err, "failed to retrieve the password from secret %s and namespace %s", basicAuth.Password.Name, basicAuth.Namespace)
}
}
request.SetBasicAuth(username, password)
}
t.Logger.WithField("url", trigger.URL).Infoln("making a http request...")
return t.Client.Do(request)
}
// ApplyPolicy applies policy on the trigger
func (t *HTTPTrigger) ApplyPolicy(resource interface{}) error {
if t.Trigger.Policy == nil || t.Trigger.Policy.Status == nil || t.Trigger.Policy.Status.Allow == nil {
return nil
}
response, ok := resource.(*http.Response)
if !ok {
return errors.New("failed to interpret the trigger execution response")
}
p := policy.NewStatusPolicy(response.StatusCode, t.Trigger.Policy.Status.Allow)
return p.ApplyPolicy()
}