forked from trustedhousesitters/roster
/
client.go
224 lines (186 loc) · 5 KB
/
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
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
package roster
import (
"time"
"errors"
"math/rand"
"net"
"os"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)
const (
HeartbeatInterval = 1000 * time.Millisecond
ServiceTTL = 5
)
var (
ErrServiceNotFound = errors.New("roster: No matching service found")
ErrLocalIpNotFound = errors.New("roster: No non loopback local IP address could be found")
)
type Service struct {
Name string
Endpoint string
Expiry int64
stopHeartbeat chan bool
}
// Unregister the service
func (s *Service) Unregister() {
s.stopHeartbeat <- true
// Pause (block) for connections to drain
time.Sleep(ServiceTTL * time.Second)
}
type ClientConfig struct {
RegistryName string
Region string
Endpoint string
}
func (cc ClientConfig) GetRegistryName() *string {
if cc.RegistryName != "" {
return aws.String(cc.RegistryName)
} else {
// Default
return aws.String("roster")
}
}
func (cc ClientConfig) GetConfig() *aws.Config {
//Explicitley set
region := cc.Region
// Environment var
if region == "" {
region = os.Getenv("AWS_REGION")
}
// Default
if region == "" {
region = "us-west-2"
}
// Create AWS config
config := aws.NewConfig().WithRegion(region)
// Check to see if DynamoDB is running locally
endpoint := cc.Endpoint
if endpoint == "" {
// Env variable must be this format for Docker Compose to work, and also must replace tcp with http
endpoint = os.Getenv("DYNAMODB_PORT")
endpoint = strings.Replace(endpoint, "tcp", "http", 1)
}
if endpoint == "" {
return config
} else {
return config.WithEndpoint(endpoint)
}
}
type Client struct {
config ClientConfig
svc *dynamodb.DynamoDB
Registry *Registry
}
func NewClient(config ClientConfig) *Client {
svc := dynamodb.New(session.New(), config.GetConfig())
Registry := NewRegistry(svc,config.GetRegistryName())
return &Client{svc: svc, config: config, Registry: Registry}
}
// Register the service in the registry
func (c *Client) Register(name string, endpoint string) (*Service,error) {
// Check whether the registry has been previously created. If not create before registration.
if exists,err := c.Registry.Exists(); err != nil {
return nil,err
} else if !exists {
if err := c.Registry.Create(); err != nil {
return nil,err
}
}
// Create Service
service := &Service{Name: name, Endpoint: endpoint, stopHeartbeat: make(chan bool)}
// Heartbeat function - updates expiry
heartbeat := func() {
// Update service Expiry based on TTL and current time
service.Expiry = time.Now().Unix() + ServiceTTL
// Update service entry in registry
if av, err := dynamodbattribute.ConvertToMap(*service); err != nil {
return
} else {
_, err := c.svc.PutItem(&dynamodb.PutItemInput{
Item: av,
TableName: c.config.GetRegistryName(),
})
if err != nil {
return
}
}
}
// Ensure call heartbeat at least once
heartbeat()
// Start goroutine to send heartbeat
go func() {
for {
select {
case <- service.stopHeartbeat:
return
default:
// Pause for interval
time.Sleep(HeartbeatInterval)
// Call heartbeat function
heartbeat()
}
}
}()
return service,nil
}
// Query the registry for named service
func (c *Client) Discover(name string) (*Service, error) {
// Make sure registry is active
if active,_ := c.Registry.IsActive(); active == true {
expressionAttributeValues := map[string]interface{}{
":NameVal": name,
":ExpiryVal": time.Now().Unix(),
}
ean := map[string]*string{
"#N": aws.String("Name"),
}
eav, err := dynamodbattribute.ConvertToMap(expressionAttributeValues)
if err != nil {
return nil,err
}
resp, err := c.svc.Query(&dynamodb.QueryInput{
TableName: c.config.GetRegistryName(),
KeyConditionExpression: aws.String("#N = :NameVal"),
FilterExpression: aws.String("Expiry > :ExpiryVal"),
ExpressionAttributeValues: eav,
ExpressionAttributeNames: ean,
})
if err != nil {
return nil, err
}
if len(resp.Items) > 0 {
// Randomly select one of the available endpoints (in effect load balancing between available endpoints)
service := Service{}
err = dynamodbattribute.ConvertFromMap(resp.Items[rand.Intn(len(resp.Items))], &service)
if err != nil {
return nil, err
}
return &service, nil
} else {
// No service found
return nil,ErrServiceNotFound
}
} else {
return nil,ErrRegistryNotActive
}
}
// Returns the non loopback local IP of the host the client is running on
func (c *Client) GetLocalIP() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "",err
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String(),nil
}
}
}
return "",ErrLocalIpNotFound
}