-
Notifications
You must be signed in to change notification settings - Fork 2
/
elasticsearch.go
67 lines (50 loc) · 1.42 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
package elasticsearch
import (
"net/http"
"strconv"
"github.com/hailo-platform/H2O/go-hailo-lib/log"
"github.com/hailo-platform/H2O/service/config"
"github.com/mattbaird/elastigo/lib"
)
func NewConnection() *elastigo.Conn {
c := elastigo.NewConn()
ch := config.SubscribeChanges()
go func() {
for _ = range ch {
loadEndpointConfig(c, nil)
}
}()
loadEndpointConfig(c, nil)
return c
}
func IndexExists(c *elastigo.Conn, index string) (bool, error) {
r, err := c.NewRequest("HEAD", "/"+index, "")
var client = r.Client
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(r.Request)
if err != nil {
return false, err
}
return !(resp.StatusCode == 404), nil
}
func loadEndpointConfig(c *elastigo.Conn, hosts []string) {
log.Info("[ElasticSearch] Loading config")
port := config.AtPath("hailo", "service", "elasticsearch", "port").AsInt(9200)
if hosts == nil {
hosts = config.AtPath("hailo", "service", "elasticsearch", "hosts").AsHostnameArray(port)
}
if len(hosts) == 0 {
hosts = append(hosts, "localhost:9200")
}
// Set these hosts in the Elasticsearch library
// This will initialise a host pool which uses an Epsilon Greedy algorithm to find healthy hosts
// and send to requests to them, and not unhealthy or slow hosts
if port == 443 {
c.Protocol = "https"
}
c.SetPort(strconv.Itoa(port))
c.SetHosts(hosts)
log.Infof("[ElasticSearch] hosts loaded: %v", hosts)
}