forked from minio/minio
/
elasticsearch.go
577 lines (503 loc) · 14.7 KB
/
elasticsearch.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
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package target
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
elasticsearch7 "github.com/elastic/go-elasticsearch/v7"
"github.com/minio/highwayhash"
"github.com/minio/minio/internal/event"
"github.com/minio/minio/internal/logger"
xnet "github.com/minio/pkg/net"
"github.com/pkg/errors"
)
// Elastic constants
const (
ElasticFormat = "format"
ElasticURL = "url"
ElasticIndex = "index"
ElasticQueueDir = "queue_dir"
ElasticQueueLimit = "queue_limit"
ElasticUsername = "username"
ElasticPassword = "password"
EnvElasticEnable = "MINIO_NOTIFY_ELASTICSEARCH_ENABLE"
EnvElasticFormat = "MINIO_NOTIFY_ELASTICSEARCH_FORMAT"
EnvElasticURL = "MINIO_NOTIFY_ELASTICSEARCH_URL"
EnvElasticIndex = "MINIO_NOTIFY_ELASTICSEARCH_INDEX"
EnvElasticQueueDir = "MINIO_NOTIFY_ELASTICSEARCH_QUEUE_DIR"
EnvElasticQueueLimit = "MINIO_NOTIFY_ELASTICSEARCH_QUEUE_LIMIT"
EnvElasticUsername = "MINIO_NOTIFY_ELASTICSEARCH_USERNAME"
EnvElasticPassword = "MINIO_NOTIFY_ELASTICSEARCH_PASSWORD"
)
// ESSupportStatus is a typed string representing the support status for
// Elasticsearch
type ESSupportStatus string
const (
// ESSUnknown is default value
ESSUnknown ESSupportStatus = "ESSUnknown"
// ESSDeprecated -> support will be removed in future
ESSDeprecated ESSupportStatus = "ESSDeprecated"
// ESSUnsupported -> we wont work with this ES server
ESSUnsupported ESSupportStatus = "ESSUnsupported"
// ESSSupported -> all good!
ESSSupported ESSupportStatus = "ESSSupported"
)
func getESVersionSupportStatus(version string) (res ESSupportStatus, err error) {
parts := strings.Split(version, ".")
if len(parts) < 1 {
err = fmt.Errorf("bad ES version string: %s", version)
return
}
majorVersion, err := strconv.Atoi(parts[0])
if err != nil {
err = fmt.Errorf("bad ES version string: %s", version)
return
}
switch {
case majorVersion <= 6:
res = ESSUnsupported
default:
res = ESSSupported
}
return
}
// magic HH-256 key as HH-256 hash of the first 100 decimals of π as utf-8 string with a zero key.
var magicHighwayHash256Key = []byte("\x4b\xe7\x34\xfa\x8e\x23\x8a\xcd\x26\x3e\x83\xe6\xbb\x96\x85\x52\x04\x0f\x93\x5d\xa3\x9f\x44\x14\x97\xe0\x9d\x13\x22\xde\x36\xa0")
// Interface for elasticsearch client objects
type esClient interface {
isAtleastV7() bool
createIndex(ElasticsearchArgs) error
ping(context.Context, ElasticsearchArgs) (bool, error)
stop()
entryExists(context.Context, string, string) (bool, error)
removeEntry(context.Context, string, string) error
updateEntry(context.Context, string, string, event.Event) error
addEntry(context.Context, string, event.Event) error
}
// ElasticsearchArgs - Elasticsearch target arguments.
type ElasticsearchArgs struct {
Enable bool `json:"enable"`
Format string `json:"format"`
URL xnet.URL `json:"url"`
Index string `json:"index"`
QueueDir string `json:"queueDir"`
QueueLimit uint64 `json:"queueLimit"`
Transport *http.Transport `json:"-"`
Username string `json:"username"`
Password string `json:"password"`
}
// Validate ElasticsearchArgs fields
func (a ElasticsearchArgs) Validate() error {
if !a.Enable {
return nil
}
if a.URL.IsEmpty() {
return errors.New("empty URL")
}
if a.Format != "" {
f := strings.ToLower(a.Format)
if f != event.NamespaceFormat && f != event.AccessFormat {
return errors.New("format value unrecognized")
}
}
if a.Index == "" {
return errors.New("empty index value")
}
if (a.Username == "" && a.Password != "") || (a.Username != "" && a.Password == "") {
return errors.New("username and password should be set in pairs")
}
return nil
}
// ElasticsearchTarget - Elasticsearch target.
type ElasticsearchTarget struct {
lazyInit lazyInit
id event.TargetID
args ElasticsearchArgs
client esClient
store Store
loggerOnce logger.LogOnce
quitCh chan struct{}
}
// ID - returns target ID.
func (target *ElasticsearchTarget) ID() event.TargetID {
return target.id
}
// IsActive - Return true if target is up and active
func (target *ElasticsearchTarget) IsActive() (bool, error) {
if err := target.init(); err != nil {
return false, err
}
return target.isActive()
}
func (target *ElasticsearchTarget) isActive() (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := target.checkAndInitClient(ctx)
if err != nil {
return false, err
}
return target.client.ping(ctx, target.args)
}
// Save - saves the events to the store if queuestore is configured, which will be replayed when the elasticsearch connection is active.
func (target *ElasticsearchTarget) Save(eventData event.Event) error {
if err := target.init(); err != nil {
return err
}
if target.store != nil {
return target.store.Put(eventData)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := target.checkAndInitClient(ctx)
if err != nil {
return err
}
err = target.send(eventData)
if xnet.IsNetworkOrHostDown(err, false) {
return errNotConnected
}
return err
}
// send - sends the event to the target.
func (target *ElasticsearchTarget) send(eventData event.Event) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if target.args.Format == event.NamespaceFormat {
objectName, err := url.QueryUnescape(eventData.S3.Object.Key)
if err != nil {
return err
}
// Calculate a hash of the key for the id of the ES document.
// Id's are limited to 512 bytes in V7+, so we need to do this.
var keyHash string
{
key := eventData.S3.Bucket.Name + "/" + objectName
if target.client.isAtleastV7() {
hh, _ := highwayhash.New(magicHighwayHash256Key) // New will never return error since key is 256 bit
hh.Write([]byte(key))
hashBytes := hh.Sum(nil)
keyHash = base64.URLEncoding.EncodeToString(hashBytes)
} else {
keyHash = key
}
}
if eventData.EventName == event.ObjectRemovedDelete {
err = target.client.removeEntry(ctx, target.args.Index, keyHash)
} else {
err = target.client.updateEntry(ctx, target.args.Index, keyHash, eventData)
}
return err
}
if target.args.Format == event.AccessFormat {
return target.client.addEntry(ctx, target.args.Index, eventData)
}
return nil
}
// Send - reads an event from store and sends it to Elasticsearch.
func (target *ElasticsearchTarget) Send(eventKey string) error {
if err := target.init(); err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := target.checkAndInitClient(ctx)
if err != nil {
return err
}
eventData, eErr := target.store.Get(eventKey)
if eErr != nil {
// The last event key in a successful batch will be sent in the channel atmost once by the replayEvents()
// Such events will not exist and wouldve been already been sent successfully.
if os.IsNotExist(eErr) {
return nil
}
return eErr
}
if err := target.send(eventData); err != nil {
if xnet.IsNetworkOrHostDown(err, false) {
return errNotConnected
}
return err
}
// Delete the event from store.
return target.store.Del(eventKey)
}
// Close - does nothing and available for interface compatibility.
func (target *ElasticsearchTarget) Close() error {
close(target.quitCh)
if target.client != nil {
// Stops the background processes that the client is running.
target.client.stop()
}
return nil
}
func (target *ElasticsearchTarget) checkAndInitClient(ctx context.Context) error {
if target.client != nil {
return nil
}
clientV7, err := newClientV7(target.args)
if err != nil {
return err
}
// Check es version to confirm if it is supported.
serverSupportStatus, version, err := clientV7.getServerSupportStatus(ctx)
if err != nil {
return err
}
switch serverSupportStatus {
case ESSUnknown:
return errors.New("unable to determine support status of ES (should not happen)")
case ESSDeprecated:
return errors.New("there is no currently deprecated version of ES in MinIO")
case ESSSupported:
target.client = clientV7
default:
// ESSUnsupported case
return fmt.Errorf("Elasticsearch version '%s' is not supported! Please use at least version 7.x.", version)
}
target.client.createIndex(target.args)
return nil
}
func (target *ElasticsearchTarget) init() error {
return target.lazyInit.Do(target.initElasticsearch)
}
func (target *ElasticsearchTarget) initElasticsearch() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := target.checkAndInitClient(ctx)
if err != nil {
if err != errNotConnected {
target.loggerOnce(context.Background(), err, target.ID().String())
}
return err
}
if target.store != nil {
streamEventsFromStore(target.store, target, target.quitCh, target.loggerOnce)
}
return nil
}
// NewElasticsearchTarget - creates new Elasticsearch target.
func NewElasticsearchTarget(id string, args ElasticsearchArgs, loggerOnce logger.LogOnce) (*ElasticsearchTarget, error) {
var store Store
if args.QueueDir != "" {
queueDir := filepath.Join(args.QueueDir, storePrefix+"-elasticsearch-"+id)
store = NewQueueStore(queueDir, args.QueueLimit)
if err := store.Open(); err != nil {
return nil, fmt.Errorf("unable to initialize the queue store of Elasticsearch `%s`: %w", id, err)
}
}
return &ElasticsearchTarget{
id: event.TargetID{ID: id, Name: "elasticsearch"},
args: args,
store: store,
loggerOnce: loggerOnce,
quitCh: make(chan struct{}),
}, nil
}
// ES Client definitions and methods
type esClientV7 struct {
*elasticsearch7.Client
}
func newClientV7(args ElasticsearchArgs) (*esClientV7, error) {
// Client options
elasticConfig := elasticsearch7.Config{
Addresses: []string{args.URL.String()},
Transport: args.Transport,
MaxRetries: 10,
}
// Set basic auth
if args.Username != "" && args.Password != "" {
elasticConfig.Username = args.Username
elasticConfig.Password = args.Password
}
// Create a client
client, err := elasticsearch7.NewClient(elasticConfig)
if err != nil {
return nil, err
}
clientV7 := &esClientV7{client}
return clientV7, nil
}
func (c *esClientV7) getServerSupportStatus(ctx context.Context) (ESSupportStatus, string, error) {
resp, err := c.Info(
c.Info.WithContext(ctx),
)
if err != nil {
return ESSUnknown, "", errNotConnected
}
defer resp.Body.Close()
m := make(map[string]interface{})
err = json.NewDecoder(resp.Body).Decode(&m)
if err != nil {
return ESSUnknown, "", fmt.Errorf("unable to get ES Server version - json parse error: %v", err)
}
if v, ok := m["version"].(map[string]interface{}); ok {
if ver, ok := v["number"].(string); ok {
status, err := getESVersionSupportStatus(ver)
return status, ver, err
}
}
return ESSUnknown, "", fmt.Errorf("Unable to get ES Server Version - got INFO response: %v", m)
}
func (c *esClientV7) isAtleastV7() bool {
return true
}
// createIndex - creates the index if it does not exist.
func (c *esClientV7) createIndex(args ElasticsearchArgs) error {
res, err := c.Indices.ResolveIndex([]string{args.Index})
if err != nil {
return err
}
defer res.Body.Close()
var v map[string]interface{}
found := false
if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
return fmt.Errorf("Error parsing response body: %v", err)
}
indices, ok := v["indices"].([]interface{})
if ok {
for _, index := range indices {
name := index.(map[string]interface{})["name"]
if name == args.Index {
found = true
break
}
}
}
if !found {
resp, err := c.Indices.Create(args.Index)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.IsError() {
err := fmt.Errorf("Create index err: %s", res.String())
return err
}
io.Copy(io.Discard, resp.Body)
return nil
}
return nil
}
func (c *esClientV7) ping(ctx context.Context, _ ElasticsearchArgs) (bool, error) {
resp, err := c.Ping(
c.Ping.WithContext(ctx),
)
if err != nil {
return false, errNotConnected
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
return !resp.IsError(), nil
}
func (c *esClientV7) entryExists(ctx context.Context, index string, key string) (bool, error) {
res, err := c.Exists(
index,
key,
c.Exists.WithContext(ctx),
)
if err != nil {
return false, err
}
io.Copy(io.Discard, res.Body)
res.Body.Close()
return !res.IsError(), nil
}
func (c *esClientV7) removeEntry(ctx context.Context, index string, key string) error {
exists, err := c.entryExists(ctx, index, key)
if err == nil && exists {
res, err := c.Delete(
index,
key,
c.Delete.WithContext(ctx),
)
if err != nil {
return err
}
defer res.Body.Close()
defer io.Copy(io.Discard, res.Body)
if res.IsError() {
return fmt.Errorf("Delete err: %s", res.String())
}
return nil
}
return err
}
func (c *esClientV7) updateEntry(ctx context.Context, index string, key string, eventData event.Event) error {
doc := map[string]interface{}{
"Records": []event.Event{eventData},
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
err := enc.Encode(doc)
if err != nil {
return err
}
res, err := c.Index(
index,
&buf,
c.Index.WithDocumentID(key),
c.Index.WithContext(ctx),
)
if err != nil {
return err
}
defer res.Body.Close()
defer io.Copy(io.Discard, res.Body)
if res.IsError() {
return fmt.Errorf("Update err: %s", res.String())
}
return nil
}
func (c *esClientV7) addEntry(ctx context.Context, index string, eventData event.Event) error {
doc := map[string]interface{}{
"Records": []event.Event{eventData},
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
err := enc.Encode(doc)
if err != nil {
return err
}
res, err := c.Index(
index,
&buf,
c.Index.WithContext(ctx),
)
if err != nil {
return err
}
defer res.Body.Close()
defer io.Copy(io.Discard, res.Body)
if res.IsError() {
return fmt.Errorf("Add err: %s", res.String())
}
return nil
}
func (c *esClientV7) stop() {
}