/
es_client.go
110 lines (98 loc) · 2.52 KB
/
es_client.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
package es
import (
"fmt"
"os"
"sync"
newrelic "github.com/newrelic/go-agent"
eelastic "github.com/topfreegames/extensions/elastic"
"github.com/topfreegames/khan/log"
"github.com/uber-go/zap"
"gopkg.in/olivere/elastic.v5"
)
// Client is the struct of an elasticsearch client
type Client struct {
Debug bool
Host string
Port int
Index string
Logger zap.Logger
Sniff bool
Client *elastic.Client
NewRelic newrelic.Application
}
var once sync.Once
var client *Client
// GetIndexName returns the name of the index
func (es *Client) GetIndexName(gameID string) string {
if es.Index != "" {
return fmt.Sprintf("%s-%s", es.Index, gameID)
}
return "khan-test"
}
// GetClient returns an elasticsearch client configured with the given the arguments
func GetClient(host string, port int, index string, sniff bool, logger zap.Logger, debug bool, newRelic newrelic.Application) *Client {
once.Do(func() {
client = &Client{
Debug: debug,
Host: host,
Port: port,
Logger: logger,
Index: index,
Sniff: sniff,
NewRelic: newRelic,
}
client.configure()
})
return client
}
// GetTestClient returns a test elasticsearch client configured with the given the arguments
func GetTestClient(host string, port int, index string, sniff bool, logger zap.Logger, debug bool) *Client {
client = &Client{
Debug: debug,
Host: host,
Port: port,
Logger: logger,
Index: index,
Sniff: sniff,
NewRelic: nil,
}
client.configure()
return client
}
// GetConfiguredClient returns an elasticsearch client with no extra configs
func GetConfiguredClient() *Client {
return client
}
func (es *Client) configure() {
es.configureClient()
}
// DestroyClient sets the elasticsearch client value to nil
func DestroyClient() {
client = nil
}
func (es *Client) configureClient() {
l := es.Logger.With(
zap.String("source", "elasticsearch"),
zap.String("operation", "configureClient"),
)
log.I(l, "Connecting to elasticsearch...", func(cm log.CM) {
cm.Write(
zap.String("elasticsearch.url", fmt.Sprintf("http://%s:%d/%s", es.Host, es.Port, es.Index)),
zap.Bool("sniff", es.Sniff),
)
})
var err error
es.Client, err = eelastic.NewClient(
elastic.SetURL(fmt.Sprintf("http://%s:%d", es.Host, es.Port)),
elastic.SetSniff(es.Sniff),
)
if err != nil {
log.E(l, "Failed to connect to elasticsearch!", func(cm log.CM) {
cm.Write(
zap.String("elasticsearch.url", fmt.Sprintf("http://%s:%d/%s", es.Host, es.Port, es.Index)),
zap.Error(err),
)
})
os.Exit(1)
}
}