-
Notifications
You must be signed in to change notification settings - Fork 493
/
http_post.go
235 lines (207 loc) · 5.67 KB
/
http_post.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
package kapacitor
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"time"
"github.com/influxdata/kapacitor/edge"
"github.com/influxdata/kapacitor/keyvalue"
"github.com/influxdata/kapacitor/models"
"github.com/influxdata/kapacitor/pipeline"
"github.com/influxdata/kapacitor/services/httppost"
"github.com/pkg/errors"
)
type HTTPPostNode struct {
node
c *pipeline.HTTPPostNode
endpoint *httppost.Endpoint
timeout time.Duration
}
// Create a new HTTPPostNode which submits received items via POST to an HTTP endpoint
func newHTTPPostNode(et *ExecutingTask, n *pipeline.HTTPPostNode, d NodeDiagnostic) (*HTTPPostNode, error) {
hn := &HTTPPostNode{
node: node{Node: n, et: et, diag: d},
c: n,
timeout: n.Timeout,
}
// Should only ever be 0 or 1 from validation of n
if len(n.URLs) == 1 {
temp, err := httppost.GetTemplate(n.URLs[0], "")
if err != nil {
return nil, errors.Wrap(err, "error in url templating")
}
e := httppost.NewEndpoint(temp, nil, httppost.BasicAuth{}, nil, nil)
hn.endpoint = e
}
// Should only ever be 0 or 1 from validation of n
if len(n.Endpoints) == 1 {
endpointName := n.Endpoints[0]
e, ok := et.tm.HTTPPostService.Endpoint(endpointName)
if !ok {
return nil, fmt.Errorf("endpoint '%s' does not exist", endpointName)
}
hn.endpoint = e
}
hn.node.runF = hn.runPost
return hn, nil
}
func (n *HTTPPostNode) runPost([]byte) error {
consumer := edge.NewGroupedConsumer(
n.ins[0],
n,
)
n.statMap.Set(statCardinalityGauge, consumer.CardinalityVar())
return consumer.Consume()
}
func (n *HTTPPostNode) NewGroup(group edge.GroupInfo, first edge.PointMeta) (edge.Receiver, error) {
g := &httpPostGroup{
n: n,
buffer: new(edge.BatchBuffer),
}
return edge.NewReceiverFromForwardReceiverWithStats(
n.outs,
edge.NewTimedForwardReceiver(n.timer, g),
), nil
}
type httpPostGroup struct {
n *HTTPPostNode
buffer *edge.BatchBuffer
}
func (g *httpPostGroup) BeginBatch(begin edge.BeginBatchMessage) (edge.Message, error) {
return nil, g.buffer.BeginBatch(begin)
}
func (g *httpPostGroup) BatchPoint(bp edge.BatchPointMessage) (edge.Message, error) {
return nil, g.buffer.BatchPoint(bp)
}
func (g *httpPostGroup) EndBatch(end edge.EndBatchMessage) (edge.Message, error) {
return g.BufferedBatch(g.buffer.BufferedBatchMessage(end))
}
func (g *httpPostGroup) BufferedBatch(batch edge.BufferedBatchMessage) (edge.Message, error) {
row := batch.ToRow()
code := g.n.doPost(row)
if g.n.c.CodeField != "" {
//Add code to all points
batch = batch.ShallowCopy()
points := make([]edge.BatchPointMessage, len(batch.Points()))
for i, bp := range batch.Points() {
fields := bp.Fields().Copy()
fields[g.n.c.CodeField] = int64(code)
points[i] = edge.NewBatchPointMessage(
fields,
bp.Tags(),
bp.Time(),
)
}
batch.SetPoints(points)
}
return batch, nil
}
func (g *httpPostGroup) Point(p edge.PointMessage) (edge.Message, error) {
row := p.ToRow()
code := g.n.doPost(row)
if g.n.c.CodeField != "" {
//Add code to point
p = p.ShallowCopy()
fields := p.Fields().Copy()
fields[g.n.c.CodeField] = int64(code)
p.SetFields(fields)
}
return p, nil
}
func (g *httpPostGroup) Barrier(b edge.BarrierMessage) (edge.Message, error) {
return b, nil
}
func (g *httpPostGroup) DeleteGroup(d edge.DeleteGroupMessage) (edge.Message, error) {
return d, nil
}
func (g *httpPostGroup) Done() {}
func (n *HTTPPostNode) doPost(row *models.Row) int {
resp, err := n.postRow(row)
if err != nil {
n.diag.Error("failed to POST data", err)
return 0
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
var err error
if n.c.CaptureResponseFlag {
var body []byte
body, err = io.ReadAll(resp.Body)
if err == nil {
// Use the body content as the error
err = errors.New(string(body))
}
} else {
err = errors.New("unknown error, use .captureResponse() to capture the HTTP response")
}
n.diag.Error("POST returned non 2xx status code", err, keyvalue.KV("code", strconv.Itoa(resp.StatusCode)))
}
return resp.StatusCode
}
func (n *HTTPPostNode) postRow(row *models.Row) (*http.Response, error) {
body := new(bytes.Buffer)
var contentType string
var mr *mappedRow
if n.endpoint.RowTemplate() != nil || n.endpoint.URL() != nil {
mr = newMappedRow(row)
}
if n.endpoint.RowTemplate() != nil {
err := n.endpoint.RowTemplate().Execute(body, mr)
if err != nil {
return nil, errors.Wrap(err, "failed to execute template")
}
} else {
result := new(models.Result)
result.Series = []*models.Row{row}
err := json.NewEncoder(body).Encode(result)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal row data json")
}
contentType = "application/json"
}
req, err := n.endpoint.NewHTTPRequest(body, mr)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal row data json")
}
// Set content type and other headers
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
for k, v := range n.c.Headers {
req.Header.Set(k, v)
}
// Set timeout
if n.timeout > 0 {
ctx, cancel := context.WithTimeout(req.Context(), n.timeout)
defer cancel()
req = req.WithContext(ctx)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
type mappedRow struct {
Name string
Tags map[string]string
Values []map[string]interface{}
}
func newMappedRow(row *models.Row) *mappedRow {
values := make([]map[string]interface{}, len(row.Values))
for i, v := range row.Values {
values[i] = make(map[string]interface{}, len(row.Columns))
for c, col := range row.Columns {
values[i][col] = v[c]
}
}
return &mappedRow{
Name: row.Name,
Tags: row.Tags,
Values: values,
}
}