-
Notifications
You must be signed in to change notification settings - Fork 0
/
tailer.go
112 lines (96 loc) · 2.49 KB
/
tailer.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
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/opensearch-project/opensearch-go/v2"
"github.com/opensearch-project/opensearch-go/v2/opensearchapi"
)
type SearchResponseHitsHit struct {
Sort []interface{} `json:"sort"`
Source map[string]interface{} `json:"_source"`
}
type SearchResponseHits struct {
Hits []SearchResponseHitsHit `json:"hits"`
}
type SearchResponse struct {
Hits SearchResponseHits `json:"hits"`
}
type Tailer struct {
Client *opensearch.Client
ClibanaConfig ClibanaConfig
SearchAfter []interface{}
}
func NewTailer(client *opensearch.Client, clibanaConfig ClibanaConfig) *Tailer {
return &Tailer{
Client: client,
ClibanaConfig: clibanaConfig,
}
}
func (t *Tailer) Tail() func(func(SearchResponseHitsHit) bool) {
size := SearchRequestSize
return func(yield func(SearchResponseHitsHit) bool) {
for {
requestBody := t.buildSearchRequestBody()
request := opensearchapi.SearchRequest{
Index: []string{t.ClibanaConfig.Index},
Body: requestBody,
Sort: []string{"@timestamp:asc"},
Size: &size,
}
response := doRequest[SearchResponse](t.Client, request)
for _, hit := range response.Hits.Hits {
t.SearchAfter = hit.Sort
if !yield(hit) {
break
}
}
if len(response.Hits.Hits) != size {
if t.ClibanaConfig.Search.Follow {
time.Sleep(TailSleep * time.Second)
} else {
break
}
}
}
}
}
func (t *Tailer) buildSearchRequestBody() *strings.Reader {
query := map[string]interface{}{
"query": map[string]interface{}{
"bool": map[string]interface{}{
"must": []interface{}{
map[string]interface{}{
"query_string": map[string]interface{}{
"query": t.ClibanaConfig.Search.Query,
},
},
map[string]interface{}{
"range": map[string]interface{}{
"@timestamp": map[string]interface{}{
"gte": t.ClibanaConfig.Search.Start,
"lte": t.ClibanaConfig.Search.End,
},
},
},
},
},
},
}
if t.SearchAfter != nil {
query["search_after"] = t.SearchAfter
}
if len(t.ClibanaConfig.Search.Fields) > 0 {
fieldNames := make([]string, 0, len(t.ClibanaConfig.Search.Fields))
for _, field := range t.ClibanaConfig.Search.Fields {
fieldNames = append(fieldNames, field.Name)
}
query["_source"] = fieldNames
}
body, err := json.Marshal(query)
if err != nil {
FatalError(fmt.Errorf("failed to marshal search request body to JSON: %w", err))
}
return strings.NewReader(string(body))
}