/
main.go
100 lines (80 loc) · 2.34 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
package main
import "encoding/json"
import "flag"
import "log"
import "time"
import "github.com/AdRoll/goamz/aws"
import "github.com/AdRoll/goamz/s3"
import "github.com/mikroio/tcp-forward-proxy/discovery"
import "github.com/mikroio/tcp-forward-proxy/proxy"
var region *string = flag.String("r", "", "aws region")
var table *string = flag.String("t", "uio-jrydberg-default", "service disovery table")
type RoutingEntry struct {
Name string `json:"name"`
ListenPort int `json:"listen_port"`
TargetService string `json:"target_service"`
}
type RoutingProxy struct {
service string
serviceDiscovery *discovery.Discovery
serviceProxy *proxy.Proxy
}
var proxies map[int]*RoutingProxy = make(map[int]*RoutingProxy)
var proxyConfig proxy.Config = proxy.Config{
MaxPoolSize: 30,
ConnectTimeout: 10,
}
func updateProxies(entries []RoutingEntry) {
// FIXME: support routes that has been gone from the routing table.
for _, entry := range entries {
routingProxy, ok := proxies[entry.ListenPort]
if ok {
if routingProxy.service == entry.TargetService {
continue
}
delete(proxies, entry.ListenPort)
routingProxy.serviceProxy.Close()
routingProxy.serviceDiscovery.Close()
}
serviceDiscovery := discovery.New(entry.TargetService,
*region, *table)
serviceDiscovery.Start()
serviceProxy := proxy.New(serviceDiscovery, proxyConfig)
err := serviceProxy.Listen(entry.ListenPort)
if err != nil {
log.Print("cannot start listen on port", entry.ListenPort)
continue
}
go serviceProxy.Accept()
proxies[entry.ListenPort] = &RoutingProxy{
service: entry.TargetService,
serviceDiscovery: serviceDiscovery,
serviceProxy: serviceProxy,
}
}
}
func main() {
flag.Parse()
if *region == "" {
*region = aws.InstanceRegion()
}
auth, err := aws.GetAuth("", "", "", time.Now())
if err != nil {
log.Panic(err)
}
s3service := s3.New(auth, aws.GetRegion(*region))
bucket := s3service.Bucket(flag.Arg(0))
for {
var entries []RoutingEntry
data, err := bucket.Get("/routing-table.json")
if err == nil {
err = json.Unmarshal(data, &entries)
if err == nil {
updateProxies(entries)
}
} else {
log.Print("no get routing table", err)
}
time.Sleep(time.Second * 10)
}
}