-
Notifications
You must be signed in to change notification settings - Fork 188
/
server.go
195 lines (176 loc) · 6.21 KB
/
server.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
package main
import (
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/docker-flow/docker-flow-proxy/metrics"
"github.com/docker-flow/docker-flow-proxy/proxy"
"github.com/docker-flow/docker-flow-proxy/server"
"github.com/docker-flow/docker-flow-proxy/actions"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
)
// Server defines interface used for creating DFP Web server
// TODO: Move to server package
type Server interface {
Execute(args []string) error
}
type serve struct {
IP string `short:"i" long:"ip" default:"0.0.0.0" env:"IP" description:"IP the server listens to."`
ListenerAddresses []string `short:"l" long:"listener-address" env:"LISTENER_ADDRESS" env-delim:"," description:"The address of the Docker Flow: Swarm Listener. The address matches the name of the Swarm service (e.g. swarm-listener)" default:""`
Port string `short:"p" long:"port" default:"8080" env:"PORT" description:"Port the server listens to."`
ServiceName string `short:"n" long:"service-name" default:"proxy" env:"SERVICE_NAME" description:"The name of the proxy service. It is used only when running in 'swarm' mode and must match the '--name' parameter used to launch the service."`
SuccessfulInitReload bool
// TODO: Remove
actions.BaseReconfigure
}
var serverImpl = serve{
ListenerAddresses: []string{},
}
var cert server.Certer = server.NewCert("/certs")
// Execute runs the Web server.
// Args are not used and are present only for compatibility reasons. Define them as an empty slice.
func (m *serve) Execute(args []string) error {
if proxy.Instance == nil {
proxy.Instance = proxy.NewHaProxy(m.TemplatesPath, m.ConfigsPath)
}
logPrintf("Starting HAProxy")
newRun().Execute([]string{})
address := fmt.Sprintf("%s:%s", m.IP, m.Port)
cert.Init()
var server2 = server.NewServer(
m.ListenerAddresses,
m.Port,
m.ServiceName,
m.ConfigsPath,
m.TemplatesPath,
cert,
)
config := server.NewConfig()
sm := server.NewMetrics("")
if err := m.reconfigure(server2); err != nil {
return err
}
metrics.SetupHandler(server.GetCreds())
logPrintf(`Starting "Docker Flow: Proxy"`)
r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/v1/docker-flow-proxy/cert", m.certPutHandler).Methods("PUT")
r.HandleFunc("/v1/docker-flow-proxy/certs", m.certsHandler)
r.HandleFunc("/v1/docker-flow-proxy/config", config.Get)
r.HandleFunc("/v1/docker-flow-proxy/metrics", sm.Get)
r.Handle("/metrics", prometheus.Handler())
r.HandleFunc("/v1/docker-flow-proxy/ping", server2.PingHandler)
r.HandleFunc("/v1/docker-flow-proxy/reconfigure", server2.ReconfigureHandler)
r.HandleFunc("/v1/docker-flow-proxy/reload", server2.ReloadHandler)
r.HandleFunc("/v1/docker-flow-proxy/remove", server2.RemoveHandler)
r.HandleFunc("/v1/docker-flow-proxy/successfulinitreload", m.SuccessfulInitReloadHandler)
r.HandleFunc("/v1/test", server2.Test1Handler)
r.HandleFunc("/v2/test", server2.Test2Handler)
return httpListenAndServe(address, r)
}
func (m *serve) reconfigure(server server.Server) error {
fetch := actions.NewFetch(m.BaseReconfigure)
if len(m.ListenerAddresses) == 1 && len(m.ListenerAddresses[0]) > 0 {
lAddr := fmt.Sprintf("http://%s:8080", m.ListenerAddresses[0])
go func() {
retryInterval := os.Getenv("RELOAD_INTERVAL")
interval, _ := time.ParseDuration(retryInterval + "ms")
repeatReload := strings.EqualFold(os.Getenv("REPEAT_RELOAD"), "true")
for range time.Tick(interval) {
if err := fetch.ReloadConfig(m.BaseReconfigure, lAddr); err != nil {
logPrintf(
"Error: Fetching config from swarm listener failed: %s. Will retry in %d seconds.",
err.Error(),
interval/time.Second,
)
} else {
m.SuccessfulInitReload = true
if !repeatReload {
break
}
}
}
}()
}
// Handlers Listener Addresses
if len(m.ListenerAddresses) > 1 {
reloadAttemptsStr := os.Getenv("RELOAD_ATTEMPTS")
retryInterval := os.Getenv("RELOAD_INTERVAL")
interval, _ := time.ParseDuration(retryInterval + "ms")
for _, addr := range m.ListenerAddresses {
if len(addr) == 0 {
continue
}
lAddr := fmt.Sprintf("http://%s:8080", addr)
go func(lAddr string) {
reloadAttempts, err := strconv.ParseInt(reloadAttemptsStr, 10, 64)
if err != nil {
reloadAttempts = 5
}
for range time.Tick(interval) {
if err := fetch.ReloadConfig(m.BaseReconfigure, lAddr); err != nil {
logPrintf(
"Error: Fetching config from swarm listener failed: %s. Will retry in %d seconds.",
err.Error(),
interval/time.Second,
)
} else {
m.SuccessfulInitReload = true
break
}
reloadAttempts = reloadAttempts - 1
if reloadAttempts <= 0 {
break
}
}
}(lAddr)
}
}
services := server.GetServicesFromEnvVars()
for _, service := range *services {
recon := actions.NewReconfigure(m.BaseReconfigure, service)
//todo: there could be only one reload after this whole loop
recon.Execute(true)
}
return nil
}
// SuccessfulInitReloadHandler responses with StatusOK when is SuccessfulInitReload otherwise
// it response with StatusInternalServerError
func (m *serve) SuccessfulInitReloadHandler(w http.ResponseWriter, req *http.Request) {
if !m.SuccessfulInitReload {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
// TODO: Move to server package
func (m *serve) certPutHandler(w http.ResponseWriter, req *http.Request) {
cert.Put(w, req)
}
// TODO: Move to server package
func (m *serve) certsHandler(w http.ResponseWriter, req *http.Request) {
cert.GetAll(w, req)
}
func (m *serve) hasPort(sd []proxy.ServiceDest) bool {
return len(sd) > 0 && len(sd[0].Port) > 0
}
func (m *serve) getBoolParam(req *http.Request, param string) bool {
value := false
if len(req.URL.Query().Get(param)) > 0 {
value, _ = strconv.ParseBool(req.URL.Query().Get(param))
}
return value
}
func (m *serve) writeBadRequest(w http.ResponseWriter, resp *server.Response, msg string) {
resp.Status = "NOK"
resp.Message = msg
w.WriteHeader(http.StatusBadRequest)
}
func (m *serve) writeInternalServerError(w http.ResponseWriter, resp *server.Response, msg string) {
resp.Status = "NOK"
resp.Message = msg
w.WriteHeader(http.StatusInternalServerError)
}