-
Notifications
You must be signed in to change notification settings - Fork 2
/
elastic.go
102 lines (82 loc) · 2.13 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
package elastic
import (
"net/url"
"errors"
"encoding/json"
"time"
"log"
"github.com/gliderlabs/registrator/bridge"
elasticapi "github.com/olivere/elastic"
)
type Container struct {
Name string `json:"container_name"`
Action string `json:"action"`
Message string `json:"message"`
Timestamp string `json:"@timestamp"`
}
func init() {
bridge.Register(new(Factory), "elastic")
}
type Factory struct{}
func (f *Factory) New(uri *url.URL) bridge.RegistryAdapter {
urls := "http://127.0.0.1:9200"
if uri.Host != "" {
urls = "http://"+uri.Host
}
client, err := elasticapi.NewClient(elasticapi.SetURL(urls))
if err != nil {
log.Fatal("elastic: ", uri.Scheme)
}
return &ElasticAdapter{client: client}
}
type ElasticAdapter struct {
client *elasticapi.Client
}
func (r *ElasticAdapter) Ping() error {
status := r.client.IsRunning()
if !status {
return errors.New("client is not Running")
}
return nil
}
func (r *ElasticAdapter) Register(service *bridge.Service) error {
serviceAsJson, err := json.Marshal(service)
if err != nil {
return err
}
timestamp := time.Now().Local().Format("2006-01-02T15:04:05.000Z07:00")
// Add a document to the index
container := Container{Name: service.Name, Action: "start", Message: string(serviceAsJson), Timestamp: timestamp}
_, err = r.client.Index().
Index("containers").
Type("audit").
BodyJson(container).
Timestamp(timestamp).
Do()
if err != nil {
return err
}
return nil
}
func (r *ElasticAdapter) Deregister(service *bridge.Service) error {
serviceAsJson, err := json.Marshal(service)
if err != nil {
return err
}
timestamp := time.Now().Local().Format("2006-01-02T15:04:05.000Z07:00")
// Add a document to the index
container := Container{Name: service.Name, Action: "stop", Message: string(serviceAsJson), Timestamp: timestamp}
_, err = r.client.Index().
Index("containers").
Type("audit").
BodyJson(container).
Timestamp(timestamp).
Do()
if err != nil {
return err
}
return nil
}
func (r *ElasticAdapter) Refresh(service *bridge.Service) error {
return nil
}