forked from pires/consul-lb-gce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
308 lines (270 loc) · 8.83 KB
/
main.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/signal"
"strings"
"sync"
"github.com/dffrntmedia/consul-lb-gce/cloud"
"github.com/dffrntmedia/consul-lb-gce/cloud/gce"
"github.com/dffrntmedia/consul-lb-gce/registry"
"github.com/dffrntmedia/consul-lb-gce/registry/consul"
"github.com/golang/glog"
)
func main() {
var configFilePath string
flag.StringVar(&configFilePath, "config", "config.json", "Configuration path")
flag.Parse()
if configFilePath == "" {
glog.Fatal("Configuration path is required")
}
glog.Infof("Reading configuration from %q...", configFilePath)
configFile, err := os.Open(configFilePath)
if err != nil {
glog.Fatal(err)
}
configBytes, err := ioutil.ReadAll(configFile)
if err != nil {
glog.Fatal(err)
}
c, configErr := parseConfig(configBytes)
if configErr != nil {
glog.Fatalf("Can't load configuration: %+v", configErr)
}
glog.Infof(
"Initializing cloud client with project ID: %q, network: %q, zone: %q...",
c.Cloud.Project,
c.Cloud.Network,
c.Cloud.Zone,
)
client, err := cloud.New(c.Cloud.Project, c.Cloud.Network, c.Cloud.Zone)
if err != nil {
glog.Fatal(err)
}
glog.Infof("Connecting to Consul at %q...", c.Consul.URL)
r, err := consul.NewRegistry(®istry.Config{
Addresses: []string{c.Consul.URL},
TagsToWatch: c.GetTagNames(),
})
if err != nil {
glog.Fatal(err)
}
updates := make(chan *registry.ServiceUpdate)
done := make(chan struct{})
glog.Info("Listening for services updates...")
go r.Run(updates, done)
go dispatchUpdates(c, client, updates, done)
// wait for Ctrl-c to stop server
osSignalChannel := make(chan os.Signal, 1)
signal.Notify(osSignalChannel, os.Interrupt, os.Kill)
<-osSignalChannel
glog.Info("Terminating...")
close(done)
glog.Info("Terminated")
}
// Dispatches updates for all services between per service channels.
func dispatchUpdates(c *configuration, cloud cloud.Cloud, updates <-chan *registry.ServiceUpdate, done chan struct{}) {
var wg sync.WaitGroup
serviceUpdatesMap := make(map[string]chan *registry.ServiceUpdate)
for {
select {
case update := <-updates:
glog.Infof("Got %q service update", update.ServiceName)
// is there a channel for service updates?
if serviceUpdates, ok := serviceUpdatesMap[update.ServiceName]; !ok {
// no handler
serviceUpdates = make(chan *registry.ServiceUpdate)
serviceUpdatesMap[update.ServiceName] = serviceUpdates
// start handler in its own goroutine
wg.Add(1)
glog.Infof("Initializing a handler for %q service updates...", update.ServiceName)
tagConfig, err := c.GetTagConfiguration(update.Tag)
if err != nil {
glog.Error(err)
continue
}
go func() {
handleServiceUpdates(c.Cloud.URLMap, cloud, tagConfig, serviceUpdates, done)
wg.Done()
}()
}
// send update to channel
serviceUpdatesMap[update.ServiceName] <- update
case <-done:
// wait for all updates are processed
wg.Wait()
return
}
}
}
// Handles service updates in a consistent way.
// It's up until service is deleted or done is closed.
func handleServiceUpdates(
urlMapName string,
client cloud.Cloud,
tagConfig *tagConfiguration,
updates <-chan *registry.ServiceUpdate,
done chan struct{},
) {
tagName := tagConfig.Name
isRunning := false
instances := make(registry.ServiceInstances)
errorTemplate := "Failed handling of %s update for service with tag %q: %+v"
for {
var err error
select {
case update := <-updates:
switch update.UpdateType {
case registry.NEW:
if isRunning {
glog.Infof("Ignored NEW update of service with tag %q since it's already running", tagName)
continue
}
if err = handleServiceNewUpdate(urlMapName, client, tagConfig); err != nil {
glog.Errorf(errorTemplate, update.UpdateType, tagName, err)
continue
}
isRunning = true
case registry.DELETED:
if !isRunning {
glog.Infof("Ignored DELETED update of service with tag %q since it's not running", tagName)
continue
}
if instances, err = handleServiceDeletedUpdate(client, tagConfig, copyServiceInstances(instances)); err != nil {
glog.Errorf(errorTemplate, update.UpdateType, tagName, err)
continue
}
isRunning = false
case registry.CHANGED:
if !isRunning {
glog.Infof("Ignored CHANGED update of service with tag %q since it's not running", tagName)
continue
}
if instances, err = handleServiceChangedUpdate(client, tagConfig, copyServiceInstances(instances), update); err != nil {
glog.Errorf(errorTemplate, update.UpdateType, tagName, err)
}
}
case <-done:
glog.Warningf("Received termination signal for service with tag %q", tagName)
return
}
}
}
func handleServiceNewUpdate(
urlMapName string,
client cloud.Cloud,
tagConfig *tagConfiguration,
) error {
tagName := tagConfig.Name
if tagConfig.Mode != REUSE_MODE {
negName := tagConfig.NetworkEndpointGroup.Name
glog.Infof("Creating network endpoint group %q...", negName)
if err := client.CreateNetworkEndpointGroup(negName); err != nil {
return fmt.Errorf("Can't create network endpoint group %q: %+v", negName, err)
}
glog.Infof("Created network endpoint group %q", negName)
hcName := tagConfig.HealthCheck.Name
glog.Infof("Creating health check %q...", hcName)
if err := client.CreateHealthCheck(hcName, tagConfig.HealthCheck.Path); err != nil {
return fmt.Errorf("Can't create health check %q: %+v", hcName, err)
}
glog.Infof("Created health check %q", hcName)
bsName := tagConfig.BackendService.Name
glog.Infof("Creating backend service %q...", bsName)
if err := client.CreateBackendService(bsName, negName, hcName, tagConfig.BackendService.Affinity, tagConfig.BackendService.CDN); err != nil {
return fmt.Errorf("Can't create backend service %q: %+v", bsName, err)
}
glog.Infof("Created backend service %q", bsName)
glog.Infof("Updating URL map %q...", urlMapName)
if err := client.UpdateURLMap(urlMapName, bsName, tagConfig.BackendService.Host, tagConfig.BackendService.Path); err != nil {
return fmt.Errorf("Can't update URL map %q: %+v", urlMapName, err)
}
glog.Infof("Updated URL map %q", urlMapName)
} else {
glog.Infof("Service with tag %q will use externally managed resources", tagName)
}
glog.Infof("Watching service with tag %q...", tagName)
return nil
}
func handleServiceDeletedUpdate(
client cloud.Cloud,
tagConfig *tagConfiguration,
instances registry.ServiceInstances,
) (registry.ServiceInstances, error) {
var toRemove []gce.NetworkEndpoint
for k, instance := range instances {
toRemove = append(toRemove, gce.NetworkEndpoint{
Instance: normalizeInstanceName(instance.Host),
IP: instance.Address,
Port: instance.Port,
})
delete(instances, k)
}
//do we have instances to remove from the NEG?
if len(toRemove) > 0 {
negName := tagConfig.NetworkEndpointGroup.Name
if err := client.DetachEndpointsFromGroup(toRemove, negName); err != nil {
return instances, fmt.Errorf("Failed detaching endpoints from %q network endpoint group: %+v", negName, err)
}
}
return instances, nil
}
func handleServiceChangedUpdate(
client cloud.Cloud,
tagConfig *tagConfiguration,
instances registry.ServiceInstances,
update *registry.ServiceUpdate,
) (registry.ServiceInstances, error) {
var toAdd, toRemove []gce.NetworkEndpoint
// finding instances to remove
for k, instance := range instances {
// Doesn't instance exist in update?
if _, ok := update.ServiceInstances[k]; !ok {
toRemove = append(toRemove, gce.NetworkEndpoint{
Instance: normalizeInstanceName(instance.Host),
IP: instance.Address,
Port: instance.Port,
})
delete(instances, k)
}
}
// finding instances to add
for k, instance := range update.ServiceInstances {
// Doesn't instance exist in running instances?
if _, ok := instances[k]; !ok {
toAdd = append(toAdd, gce.NetworkEndpoint{
Instance: normalizeInstanceName(instance.Host),
IP: instance.Address,
Port: instance.Port,
})
instances[k] = instance
}
}
//do we have instances to remove from the NEG?
if len(toRemove) > 0 {
negName := tagConfig.NetworkEndpointGroup.Name
if err := client.DetachEndpointsFromGroup(toRemove, negName); err != nil {
return instances, fmt.Errorf("Failed detaching endpoints from %q network endpoint group: %+v", negName, err)
}
}
// do we have new instances to add to the NEG?
if len(toAdd) > 0 {
negName := tagConfig.NetworkEndpointGroup.Name
if err := client.AttachEndpointsToGroup(toAdd, negName); err != nil {
return instances, fmt.Errorf("Failed adding endpoints to %q network endpoint group: %+v", negName, err)
}
}
return instances, nil
}
func normalizeInstanceName(name string) string {
return strings.Split(name, ".")[0]
}
func copyServiceInstances(m registry.ServiceInstances) registry.ServiceInstances {
copy := registry.ServiceInstances{}
for key, value := range m {
copy[key] = value
}
return copy
}