forked from raystack/meteor
/
elastic.go
205 lines (181 loc) · 4.89 KB
/
elastic.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
package elastic
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"io"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
"github.com/goto/meteor/models"
v1beta2 "github.com/goto/meteor/models/gotocompany/assets/v1beta2"
"github.com/goto/meteor/plugins"
"github.com/goto/meteor/registry"
"github.com/goto/salt/log"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/structpb"
)
// init registers the extractor to catalog
func init() {
if err := registry.Extractors.Register("elastic", func() plugins.Extractor {
return New(plugins.GetLog())
}); err != nil {
panic(err)
}
}
//go:embed README.md
var summary string
type Config struct {
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
Host string `mapstructure:"host" validate:"required"`
}
var sampleConfig = `
user: "elastic"
password: "changeme"
host: elastic_server`
var info = plugins.Info{
Description: "Search engine based on the Lucene library.",
SampleConfig: sampleConfig,
Summary: summary,
Tags: []string{"oss", "extractor"},
}
// Extractor manages the extraction of data from elastic
type Extractor struct {
plugins.BaseExtractor
config Config
logger log.Logger
client *elasticsearch.Client
}
// New returns a pointer to an initialized Extractor Object
func New(logger log.Logger) *Extractor {
e := &Extractor{
logger: logger,
}
e.BaseExtractor = plugins.NewBaseExtractor(info, &e.config)
return e
}
// Init initializes the extractor
func (e *Extractor) Init(ctx context.Context, config plugins.Config) error {
if err := e.BaseExtractor.Init(ctx, config); err != nil {
return err
}
// build elasticsearch client
cfg := elasticsearch.Config{
Addresses: []string{
e.config.Host,
},
Username: e.config.User,
Password: e.config.Password,
}
var err error
if e.client, err = elasticsearch.NewClient(cfg); err != nil {
return fmt.Errorf("create client: %w", err)
}
return nil
}
// Extract extracts the data from the elastic server
// and collected through the emitter
func (e *Extractor) Extract(ctx context.Context, emit plugins.Emit) error {
res, err := e.client.Cluster.Health(
e.client.Cluster.Health.WithLevel("indices"),
e.client.Cluster.Health.WithContext(ctx),
)
if err != nil {
return fmt.Errorf("fetch cluster info: %w", err)
}
defer drainBody(res)
var r struct {
Indices map[string]interface{} `json:"indices"`
}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
return fmt.Errorf("decode cluster info: %w", err)
}
for indexName := range r.Indices {
if err := e.buildAsset(ctx, indexName, emit); err != nil {
return err
}
}
return nil
}
func (e *Extractor) buildAsset(ctx context.Context, indexName string, emit plugins.Emit) error {
docProperties, err := e.listIndexInfo(indexName)
if err != nil {
return err
}
var columns []*v1beta2.Column
for field, fieldMapping := range docProperties {
var typ string
if s, ok := fieldMapping["type"].(string); ok {
typ = s
}
columns = append(columns, &v1beta2.Column{
Name: field,
DataType: typ,
})
}
countRes, err := e.client.Search(
e.client.Search.WithIndex(indexName),
e.client.Search.WithContext(ctx),
)
if err != nil {
return err
}
defer drainBody(countRes)
var t struct {
Hits struct {
Hits []interface{} `json:"hits"`
} `json:"hits"`
}
if err := json.NewDecoder(countRes.Body).Decode(&t); err != nil {
return err
}
docCount := len(t.Hits.Hits)
table, err := anypb.New(&v1beta2.Table{
Columns: columns,
Attributes: &structpb.Struct{}, // ensure attributes don't get overwritten if present
Profile: &v1beta2.TableProfile{
TotalRows: int64(docCount),
},
})
if err != nil {
return fmt.Errorf("create Any struct for table: %w", err)
}
emit(models.NewRecord(&v1beta2.Asset{
Urn: models.NewURN("elasticsearch", e.UrnScope, "index", indexName),
Name: indexName,
Type: "table",
Service: "elasticsearch",
Data: table,
}))
return nil
}
// listIndexInfo returns the properties of the index
func (e *Extractor) listIndexInfo(index string) (map[string]map[string]interface{}, error) {
res, err := e.client.Indices.GetMapping(
e.client.Indices.GetMapping.WithIndex(index),
)
if err != nil {
return nil, fmt.Errorf("retrieve index: %w", err)
}
defer drainBody(res)
var r map[string]struct {
Mappings struct {
Properties map[string]map[string]interface{} `json:"properties"`
} `json:"mappings"`
}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
return nil, err
}
return r[index].Mappings.Properties, nil
}
// drainBody drains and closes the response body to avoid the following
// gotcha:
// http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/index.html#close_http_resp_body
func drainBody(resp *esapi.Response) {
if resp == nil {
return
}
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}