-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (72 loc) · 1.8 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
package main
import (
"bytes"
"log"
"net"
"net/http"
"os"
"os/exec"
"reflect"
"sort"
"strconv"
"time"
"github.com/ddtmachado/lb-dxp/traefik"
)
var configBackends = make(map[string][]net.IP)
func lookupEnv(env string) string {
envValue, hasEnv := os.LookupEnv(env)
if !hasEnv {
log.Fatalf("%s variable not set", env)
}
return envValue
}
func main() {
serviceName := lookupEnv("SERVICE_NAME")
backendPort := lookupEnv("BACKEND_PORT")
traefikAddress := lookupEnv("TRAEFIK_ADDRESS")
waitInterval, err := strconv.Atoi(lookupEnv("WAIT_INTERVAL"))
if err != nil {
log.Fatalf("Wrong value for WAIT_INTERVAL variable %v", waitInterval)
}
traefikBinary, lookErr := exec.LookPath("traefik")
if lookErr != nil {
log.Fatal("Could not find the traefik binary")
}
cmd := exec.Command(traefikBinary,
"--api",
"--rest",
"--logLevel=INFO",
"--accessLog",
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
log.Fatalf("Unable to start traefik process: %v", err)
}
for {
time.Sleep(time.Duration(waitInterval) * time.Second)
serverIPs, err := net.LookupIP(serviceName)
if err != nil {
log.Fatal("Couldn't get service addresses")
}
sort.Slice(serverIPs, func(i, j int) bool {
return bytes.Compare(serverIPs[i], serverIPs[j]) < 0
})
currentIPs := configBackends[serviceName]
if reflect.DeepEqual(serverIPs, currentIPs) {
continue
}
configBackends[serviceName] = serverIPs
data, err := traefik.NewJsonConfig(serviceName, backendPort, serverIPs)
log.Printf("Traefik json payload: %s", data)
payload := bytes.NewReader(data)
request, err := http.NewRequest(http.MethodPut, traefikAddress, payload)
client := &http.Client{}
_, err = client.Do(request)
if err != nil {
log.Fatal(err)
}
log.Printf("Traefik config updated")
}
}