This repository has been archived by the owner on Oct 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 183
/
file.go
98 lines (81 loc) · 2.23 KB
/
file.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
// Package file is a file-based observer that is primarily meant for
// development and test purposes. It will watch a json file, which should
// consist of an array of serialized service instances.
package file
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/signalfx/signalfx-agent/internal/core/config"
"github.com/signalfx/signalfx-agent/internal/core/services"
"github.com/signalfx/signalfx-agent/internal/observers"
log "github.com/sirupsen/logrus"
)
const (
observerType = "file"
)
var logger = log.WithFields(log.Fields{"observerType": observerType})
// Config for the file observer
type Config struct {
config.ObserverConfig
Path string `default:"/etc/signalfx/service_instances.json"`
}
// File observer plugin
type File struct {
serviceCallbacks *observers.ServiceCallbacks
serviceDiffer *observers.ServiceDiffer
config *Config
}
func init() {
observers.Register(observerType, func(cbs *observers.ServiceCallbacks) interface{} {
return &File{
serviceCallbacks: cbs,
}
}, &Config{})
}
// Configure the docker client
func (file *File) Configure(config *Config) error {
file.config = config
if file.serviceDiffer != nil {
file.serviceDiffer.Stop()
}
file.serviceDiffer = &observers.ServiceDiffer{
DiscoveryFn: file.discover,
IntervalSeconds: 5,
Callbacks: file.serviceCallbacks,
}
file.serviceDiffer.Start()
return nil
}
// Discover services from a file
func (file *File) discover() []services.Endpoint {
if _, err := os.Stat(file.config.Path); err != nil {
return nil
}
var instances []*services.ContainerEndpoint
jsonContent, err := ioutil.ReadFile(file.config.Path)
if err != nil {
logger.WithFields(log.Fields{
"error": err,
"filePath": file.config.Path,
}).Error("Could not read service file")
return nil
}
if err := json.Unmarshal(jsonContent, &instances); err != nil {
logger.WithFields(log.Fields{
"error": err,
"filePath": file.config.Path,
}).Error("Could not parse service json")
}
var out []services.Endpoint
for i := range instances {
out = append(out, services.Endpoint(instances[i]))
}
return out
}
// Shutdown the service differ routine
func (file *File) Shutdown() {
if file.serviceDiffer != nil {
file.serviceDiffer.Stop()
}
}