-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
123 lines (96 loc) · 2.24 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
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"github.com/coreos/pkg/flagutil"
"github.com/golang/glog"
consulapi "github.com/hashicorp/consul/api"
"github.com/lightcode/kube2consul/core"
"github.com/lightcode/kube2consul/plugins"
// Plugins need to be imported for their init() to get executed and them to register
_ "github.com/lightcode/kube2consul/plugins/services"
)
const ServiceLeaderKey = "lock/services_leader"
var (
consulClient *api.ConsulBackend
consulLock *consulapi.Lock
opts CmdLineOpts
sigch chan os.Signal
)
type CmdLineOpts struct {
kubeAPI string
consulAPI string
}
func init() {
flag.StringVar(&opts.kubeAPI, "kubernetes-api", "http://127.0.0.1:8080", "Kubernetes API URL")
flag.StringVar(&opts.consulAPI, "consul-api", "127.0.0.1:8500", "Consul API URL")
}
func run() {
kubeWatcher := api.NewKubeWatcher(opts.kubeAPI)
db := api.NewDatabase(opts.kubeAPI)
pm := plugins.NewPluginManager(db, consulClient, kubeWatcher)
pm.Initialize()
db.UpdateDatabase()
pm.Sync()
ch := make(chan struct{})
go db.StartWatching(ch)
go kubeWatcher.Start()
for {
select {
case s := <-sigch:
if s == syscall.SIGHUP {
glog.Info("User trigger an update")
pm.Sync()
}
case <-ch:
pm.Sync()
}
}
}
func attemptGetLock() <-chan struct{} {
glog.Info("Attempting to get lock...")
lockch, err := consulLock.Lock(nil)
if err != nil {
glog.Fatal(err)
}
glog.Info("This instance has got lock")
return lockch
}
func releaseLock() {
consulLock.Unlock()
glog.Info("Lock has been released")
}
func main() {
flag.Parse()
flagutil.SetFlagsFromEnv(flag.CommandLine, "K2C")
consulClient = api.NewConsulClient(opts.consulAPI)
consul := consulClient.Client()
var err error
consulLock, err = consul.LockOpts(&consulapi.LockOptions{
Key: ServiceLeaderKey,
SessionName: "kube2consul lock",
})
if err != nil {
glog.Fatal(err)
}
defer releaseLock()
sigch = make(chan os.Signal, 1)
signal.Notify(sigch,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
LOCK:
lockch := attemptGetLock()
go run()
select {
case <-lockch:
goto LOCK
case s := <-sigch:
if s == syscall.SIGINT || s == syscall.SIGTERM || s == syscall.SIGQUIT {
return
}
}
}