-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathelasticClient.go
More file actions
404 lines (333 loc) · 10.1 KB
/
elasticClient.go
File metadata and controls
404 lines (333 loc) · 10.1 KB
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package client
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
"github.com/multiversx/mx-chain-es-indexer-go/data"
"github.com/multiversx/mx-chain-es-indexer-go/process/dataindexer"
logger "github.com/multiversx/mx-chain-logger-go"
)
// TODO add more unit tests
const (
esConflictsPolicy = "proceed"
errPolicyAlreadyExists = "document already exists"
)
var log = logger.GetOrCreate("indexer/client")
type (
responseErrorHandler func(res *esapi.Response) error
objectsMap = map[string]interface{}
)
type elasticClient struct {
elasticBaseUrl string
client *elasticsearch.Client
// countScroll is used to be incremented after each scroll so the scroll duration is different each time,
// bypassing any possible caching based on the same request
countScroll int
}
// NewElasticClient will create a new instance of elasticClient
func NewElasticClient(cfg elasticsearch.Config) (*elasticClient, error) {
if len(cfg.Addresses) == 0 {
return nil, dataindexer.ErrNoElasticUrlProvided
}
es, err := elasticsearch.NewClient(cfg)
if err != nil {
return nil, err
}
ec := &elasticClient{
client: es,
elasticBaseUrl: cfg.Addresses[0],
}
return ec, nil
}
// CheckAndCreateTemplate creates an index template if it does not already exist
func (ec *elasticClient) CheckAndCreateTemplate(templateName string, template *bytes.Buffer) error {
if ec.templateExists(templateName) {
return nil
}
return ec.createIndexTemplate(templateName, template)
}
// CheckAndCreatePolicy creates a new index policy if it does not already exist
func (ec *elasticClient) CheckAndCreatePolicy(policyName string, policy *bytes.Buffer) error {
if ec.PolicyExists(policyName) {
return nil
}
return ec.createPolicy(policyName, policy)
}
// CheckAndCreateIndex creates a new index if it does not already exist
func (ec *elasticClient) CheckAndCreateIndex(indexName string) error {
if ec.indexExists(indexName) {
return nil
}
return ec.createIndex(indexName)
}
// PutMappings will put the provided mappings to a given index
func (ec *elasticClient) PutMappings(indexName string, mappings *bytes.Buffer) error {
res, err := ec.client.Indices.PutMapping(
mappings,
ec.client.Indices.PutMapping.WithIndex(indexName),
)
if err != nil {
return err
}
if res.IsError() {
return errors.New(res.String())
}
return nil
}
// CheckAndCreateAlias creates a new alias if it does not already exist
func (ec *elasticClient) CheckAndCreateAlias(alias string, indexName string) error {
if ec.aliasExists(alias) {
return nil
}
return ec.createAlias(alias, indexName)
}
// DoBulkRequest will do a bulk of request to elastic server
func (ec *elasticClient) DoBulkRequest(ctx context.Context, buff *bytes.Buffer, index string) error {
reader := bytes.NewReader(buff.Bytes())
options := make([]func(*esapi.BulkRequest), 0)
if index != "" {
options = append(options, ec.client.Bulk.WithIndex(index))
}
options = append(options, ec.client.Bulk.WithContext(ctx))
res, err := ec.client.Bulk(
reader,
options...,
)
if err != nil {
log.Warn("elasticClient.DoBulkRequest",
"indexer do bulk request no response", err.Error())
return err
}
return elasticBulkRequestResponseHandler(res)
}
// DoMultiGet wil do a multi get request to Elasticsearch server
func (ec *elasticClient) DoMultiGet(ctx context.Context, ids []string, index string, withSource bool, resBody interface{}) error {
obj := getDocumentsByIDsQuery(ids, withSource)
body, err := encode(obj)
if err != nil {
return err
}
res, err := ec.client.Mget(
&body,
ec.client.Mget.WithIndex(index),
ec.client.Mget.WithContext(ctx),
)
if err != nil {
log.Warn("elasticClient.DoMultiGet",
"cannot do multi get no response", err.Error())
return err
}
err = parseResponse(res, &resBody, elasticDefaultErrorResponseHandler)
if err != nil {
log.Warn("elasticClient.DoMultiGet",
"error parsing response", err.Error())
return err
}
return nil
}
// DoQueryRemove will do a query remove to elasticsearch server
func (ec *elasticClient) DoQueryRemove(ctx context.Context, index string, body *bytes.Buffer) error {
err := ec.doRefresh(index)
if err != nil {
log.Warn("elasticClient.doRefresh", "cannot do refresh", err)
}
writeIndex, err := ec.getWriteIndex(index)
if err != nil {
log.Warn("elasticClient.getWriteIndex", "cannot do get write index", err)
return err
}
res, err := ec.client.DeleteByQuery(
[]string{writeIndex},
body,
ec.client.DeleteByQuery.WithIgnoreUnavailable(true),
ec.client.DeleteByQuery.WithConflicts(esConflictsPolicy),
ec.client.DeleteByQuery.WithContext(ctx),
)
if err != nil {
log.Warn("elasticClient.DoQueryRemove", "cannot do query remove", err)
return err
}
err = parseResponse(res, nil, elasticDefaultErrorResponseHandler)
if err != nil {
log.Warn("elasticClient.DoQueryRemove", "error parsing response", err)
return err
}
return nil
}
func (ec *elasticClient) doRefresh(index string) error {
res, err := ec.client.Indices.Refresh(
ec.client.Indices.Refresh.WithIndex(index),
ec.client.Indices.Refresh.WithIgnoreUnavailable(true),
)
if err != nil {
return err
}
return parseResponse(res, nil, elasticDefaultErrorResponseHandler)
}
// TemplateExists checks weather a template is already created
func (ec *elasticClient) templateExists(index string) bool {
res, err := ec.client.Indices.ExistsTemplate([]string{index})
return exists(res, err)
}
// IndexExists checks if a given index already exists
func (ec *elasticClient) indexExists(index string) bool {
res, err := ec.client.Indices.Exists([]string{index})
return exists(res, err)
}
// PolicyExists checks if a policy was already created
func (ec *elasticClient) PolicyExists(policy string) bool {
policyRoute := fmt.Sprintf(
"%s/%s/ism/policies/%s",
ec.elasticBaseUrl,
kibanaPluginPath,
policy,
)
req := newRequest(http.MethodGet, policyRoute, nil)
res, err := ec.client.Transport.Perform(req)
if err != nil {
log.Warn("elasticClient.PolicyExists",
"error performing request", err.Error())
return false
}
response := &esapi.Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
existsRes := &data.Response{}
err = parseResponse(response, existsRes, kibanaResponseErrorHandler)
if err != nil {
log.Warn("elasticClient.PolicyExists",
"error returned by kibana api", err.Error())
return false
}
return existsRes.Status == http.StatusConflict
}
// AliasExists checks if an index alias already exists
func (ec *elasticClient) aliasExists(alias string) bool {
aliasRoute := fmt.Sprintf(
"/_alias/%s",
alias,
)
req := newRequest(http.MethodHead, aliasRoute, nil)
res, err := ec.client.Transport.Perform(req)
if err != nil {
log.Warn("elasticClient.AliasExists",
"error performing request", err.Error())
return false
}
response := &esapi.Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
return exists(response, nil)
}
// CreateIndex creates an elasticsearch index
func (ec *elasticClient) createIndex(index string) error {
res, err := ec.client.Indices.Create(index)
if err != nil {
return err
}
return parseResponse(res, nil, elasticDefaultErrorResponseHandler)
}
// CreatePolicy creates a new policy for elastic indexes. Policies define rollover parameters
func (ec *elasticClient) createPolicy(policyName string, policy *bytes.Buffer) error {
policyRoute := fmt.Sprintf(
"%s/_opendistro/_ism/policies/%s",
ec.elasticBaseUrl,
policyName,
)
req := newRequest(http.MethodPut, policyRoute, policy)
req.Header[headerContentType] = headerContentTypeJSON
req.Header[headerXSRF] = []string{"false"}
res, err := ec.client.Transport.Perform(req)
if err != nil {
return err
}
response := &esapi.Response{
StatusCode: res.StatusCode,
Body: res.Body,
Header: res.Header,
}
existsRes := &data.Response{}
err = parseResponse(response, existsRes, kibanaResponseErrorHandler)
if err != nil {
return err
}
errStr := fmt.Sprintf("%v", existsRes.Error)
if existsRes.Status == http.StatusConflict && !strings.Contains(errStr, errPolicyAlreadyExists) {
return dataindexer.ErrCouldNotCreatePolicy
}
return nil
}
// CreateIndexTemplate creates an elasticsearch index template
func (ec *elasticClient) createIndexTemplate(templateName string, template io.Reader) error {
res, err := ec.client.Indices.PutIndexTemplate(templateName, template)
if err != nil {
return err
}
return parseResponse(res, nil, elasticDefaultErrorResponseHandler)
}
// CreateAlias creates an index alias
func (ec *elasticClient) createAlias(alias string, index string) error {
res, err := ec.client.Indices.PutAlias([]string{index}, alias)
if err != nil {
return err
}
return parseResponse(res, nil, elasticDefaultErrorResponseHandler)
}
func (ec *elasticClient) getWriteIndex(alias string) (string, error) {
res, err := ec.client.Indices.GetAlias(
ec.client.Indices.GetAlias.WithIndex(alias),
)
if err != nil {
return "", err
}
var indexData map[string]struct {
Aliases map[string]struct {
IsWriteIndex bool `json:"is_write_index"`
} `json:"aliases"`
}
err = parseResponse(res, &indexData, elasticDefaultErrorResponseHandler)
if err != nil {
return "", err
}
for index, details := range indexData {
if len(indexData) == 1 {
return index, nil
}
for _, indexAlias := range details.Aliases {
if indexAlias.IsWriteIndex {
return index, nil
}
}
}
return alias, nil
}
// UpdateByQuery will update all the documents that match the provided query from the provided index
func (ec *elasticClient) UpdateByQuery(ctx context.Context, index string, buff *bytes.Buffer) error {
reader := bytes.NewReader(buff.Bytes())
res, err := ec.client.UpdateByQuery(
[]string{index},
ec.client.UpdateByQuery.WithBody(reader),
ec.client.UpdateByQuery.WithContext(ctx),
)
if err != nil {
return err
}
if res.IsError() {
return fmt.Errorf("%s", res.String())
}
return parseResponse(res, nil, elasticDefaultErrorResponseHandler)
}
// IsInterfaceNil returns true if there is no value under the interface
func (ec *elasticClient) IsInterfaceNil() bool {
return ec == nil
}