-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathinit.go
317 lines (248 loc) · 7.71 KB
/
init.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package splunk
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/orlangure/gnomock"
)
var errConflict = fmt.Errorf("409: conflict")
// Event is a type used during Splunk initialization. Pass events to WithValues
// to ingest them into the container before the control over it is passed to
// the caller.
type Event struct {
// Event is the actual log entry. Can be any format
Event string `json:"event"`
// Index is the name of index to ingest the log into. If the index does not
// exist, it will be created
Index string `json:"index"`
// Source will be used as "source" value of this event in Splunk
Source string `json:"source"`
// SourceType will be used as "sourcetype" value of this event in Splunk
SourceType string `json:"sourcetype"`
// Time represents event timestamp in seconds, milliseconds or nanoseconds
// (and maybe even in microseconds, whatever splunk recognizes)
Time int64 `json:"time"`
}
func (p *P) initf() gnomock.InitFunc {
return func(ctx context.Context, c *gnomock.Container) (err error) {
if p.ValuesFile != "" {
f, err := os.Open(p.ValuesFile)
if err != nil {
return fmt.Errorf("can't open values file '%s': %w", p.ValuesFile, err)
}
defer func() {
closeErr := f.Close()
if err == nil && closeErr != nil {
err = closeErr
}
}()
events := make([]Event, 0)
decoder := json.NewDecoder(f)
for {
var e Event
err = decoder.Decode(&e)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return fmt.Errorf("can't read initial event: %w", err)
}
events = append(events, e)
}
p.Values = append(events, p.Values...)
}
err = Ingest(ctx, c, p.AdminPassword, p.Values...)
if err != nil {
return fmt.Errorf("can't ingest events: %w", err)
}
return nil
}
}
// Ingest adds the provided events to splunk container. Use the same password
// you provided in WithPassword. Send as many events as you like, this function
// only returns when all the events were indexed, or when the context is timed
// out.
func Ingest(ctx context.Context, c *gnomock.Container, adminPassword string, events ...Event) error {
countEvents := eventCounter(ctx, c, adminPassword)
initialCount, err := countEvents()
if err != nil {
return fmt.Errorf("can't get initial event count: %w", err)
}
if err := ingestEvents(ctx, c, adminPassword, events); err != nil {
return fmt.Errorf("failed to ingest events: %w", err)
}
var (
lastErr error
lastCount int
expectedCount = initialCount + len(events)
)
for {
select {
case <-ctx.Done():
return fmt.Errorf("event count didn't match: want %d, got %d; last error: %w",
expectedCount, lastCount, errors.Join(lastErr, context.Canceled))
default:
lastCount, lastErr = countEvents()
if lastErr == nil && lastCount == expectedCount {
return nil
}
time.Sleep(time.Millisecond * 250)
}
}
}
func ingestEvents(ctx context.Context, c *gnomock.Container, adminPassword string, events []Event) error {
postFormWithPassword := requestWithAuth(ctx, http.MethodPost, adminPassword, false)
ensureIndex := indexRegistry(postFormWithPassword, c.Address(APIPort))
ingestEvent, err := eventForwarder(ctx, c, adminPassword)
if err != nil {
return fmt.Errorf("can't setup event ingestion: %w", err)
}
for _, e := range events {
select {
case <-ctx.Done():
return context.Canceled
default:
if err := ensureIndex(e.Index); err != nil {
return err
}
if err := ingestEvent(e); err != nil {
return err
}
}
}
return nil
}
func issueToken(post postFunc, addr string) (string, error) {
newTokenURL := fmt.Sprintf("https://%s/services/data/inputs/http?output_mode=json", addr)
tokenName := fmt.Sprintf("gnomock-%d", time.Now().UnixNano())
data := url.Values{}
data.Set("name", tokenName)
buf := bytes.NewBufferString(data.Encode())
bs, err := post(newTokenURL, buf)
if err != nil {
return "", fmt.Errorf("can't create new HEC token: %w", err)
}
r := splunkTokenResponse{}
err = json.Unmarshal(bs, &r)
if err != nil {
return "", fmt.Errorf("can't unmarshal HEC token: %w", err)
}
return r.Entry[0].Content.Token, nil
}
func indexRegistry(post postFunc, addr string) func(string) error {
indexes := map[string]bool{"main": true}
uri := fmt.Sprintf("https://%s/services/data/indexes?output_mode=json", addr)
return func(indexName string) error {
if _, ok := indexes[indexName]; !ok {
_, err := post(uri, bytes.NewBufferString("name="+indexName))
if err != nil && !errors.Is(err, errConflict) {
return fmt.Errorf("can't create index: %w", err)
}
indexes[indexName] = true
}
return nil
}
}
type ingestFunc func(Event) error
func eventForwarder(ctx context.Context, c *gnomock.Container, adminPassword string) (ingestFunc, error) {
postFormWithPassword := requestWithAuth(ctx, http.MethodPost, adminPassword, false)
collectorToken, err := issueToken(postFormWithPassword, c.Address(APIPort))
if err != nil {
return nil, fmt.Errorf("can't issue new HEC token: %w", err)
}
postJSONWithToken := requestWithAuth(ctx, http.MethodPost, collectorToken, true)
return func(e Event) error {
uri := fmt.Sprintf("https://%s/services/collector?output_mode=json", c.Address(CollectorPort))
eventBytes, err := json.Marshal(e)
if err != nil {
return fmt.Errorf("can't marshal event to json: %w", err)
}
_, err = postJSONWithToken(uri, bytes.NewBuffer(eventBytes))
if err != nil {
return err
}
return nil
}, nil
}
type countFunc func() (int, error)
func eventCounter(ctx context.Context, c *gnomock.Container, adminPassword string) countFunc {
return func() (int, error) {
postFormWithPassword := requestWithAuth(ctx, http.MethodPost, adminPassword, false)
uri := fmt.Sprintf("https://%s/services/search/jobs/export", c.Address(APIPort))
data := url.Values{}
data.Add("search", "search index=* | stats count")
data.Add("output_mode", "json")
bs, err := postFormWithPassword(uri, bytes.NewBufferString(data.Encode()))
if err != nil {
return 0, err
}
var response splunkSearchcResponse
err = json.Unmarshal(bs, &response)
if err != nil {
return 0, err
}
countStr, ok := response.Result["count"]
if !ok {
return 0, err
}
count, err := strconv.Atoi(fmt.Sprintf("%s", countStr))
if err != nil {
return 0, err
}
return count, nil
}
}
type postFunc func(string, *bytes.Buffer) ([]byte, error)
func requestWithAuth(ctx context.Context, method, password string, isJSON bool) postFunc {
client := insecureClient()
return func(uri string, buf *bytes.Buffer) (bs []byte, err error) {
req, err := http.NewRequestWithContext(ctx, method, uri, buf)
if err != nil {
return nil, fmt.Errorf("can't create request: %w", err)
}
req.SetBasicAuth("admin", password)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if isJSON {
req.Header.Set("Content-Type", "application/json")
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer func() {
closeErr := resp.Body.Close()
if err == nil && closeErr != nil {
err = fmt.Errorf("can't close response body: %w", closeErr)
}
}()
bs, err = io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("can't read response body: %w", err)
}
if resp.StatusCode == http.StatusConflict {
return nil, errConflict
}
if resp.StatusCode >= http.StatusBadRequest {
return nil, errors.New(resp.Status + ": " + string(bs))
}
return bs, nil
}
}
type splunkTokenResponse struct {
Entry []struct {
Content struct {
Token string `json:"token"`
} `json:"content"`
} `json:"entry"`
}
type splunkSearchcResponse struct {
Result map[string]interface{} `json:"result"`
}