/
service.go
333 lines (289 loc) · 8.02 KB
/
service.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright (c) 2016 Pulcy.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package service
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"strconv"
"sync/atomic"
"syscall"
"time"
"github.com/op/go-logging"
"github.com/pulcy/robin/service/acme"
"github.com/pulcy/robin/service/backend"
)
const (
osExitDelay = time.Second * 3
confPerm = os.FileMode(0664) // rw-rw-r
refreshDelay = time.Second * 5
)
type ServiceConfig struct {
HaproxyConfPath string
HaproxyPath string
HaproxyPidPath string
StatsPort int
StatsUser string
StatsPassword string
StatsSslCert string
PrivateStatsPort int
SslCertsFolder string
ForceSsl bool
PrivateHost string
PublicHost string
PrivateTcpSslCert string // Name of SSL certificate used for private tcp connections
ExcludePublic bool // If set, all public frontends are excluded
ExcludePrivate bool // If set, all private frontends are excluded
}
type ServiceDependencies struct {
Logger *logging.Logger
Backend backend.Backend
AcmeService acme.AcmeService
}
type Service struct {
ServiceConfig
ServiceDependencies
signalCounter uint32
lastConfig string
lastPid int
changeCounter uint32
}
// NewService creates a new service instance.
func NewService(config ServiceConfig, deps ServiceDependencies) *Service {
if config.HaproxyPath == "" {
config.HaproxyPath = "haproxy"
}
if config.HaproxyPidPath == "" {
config.HaproxyPidPath = "/var/run/haproxy.pid"
}
return &Service{
ServiceConfig: config,
ServiceDependencies: deps,
}
}
// Run starts the service and waits for OS signals to terminate it.
func (s *Service) Run() {
go s.backendMonitorLoop()
go s.configLoop()
go func() {
time.Sleep(time.Second)
s.TriggerUpdate()
}()
s.listenSignals()
}
// configLoop updates the haproxy config, and then waits
// for changes in the backend.
func (s *Service) configLoop() {
var lastChangeCounter uint32
for {
currentChangeCounter := atomic.LoadUint32(&s.changeCounter)
if currentChangeCounter > lastChangeCounter {
if err := s.updateHaproxy(); err != nil {
s.Logger.Errorf("Failed to update haproxy: %#v", err)
} else {
// Success
lastChangeCounter = currentChangeCounter
}
}
select {
case <-time.After(refreshDelay):
}
}
}
// backendMonitorLoop monitors the configuration backend for changes.
// When it detects a change, it set a dirty flag.
func (s *Service) backendMonitorLoop() {
for {
if err := s.Backend.Watch(); err != nil {
s.Logger.Errorf("Failed to watch for backend changes: %#v", err)
}
s.TriggerUpdate()
}
}
// TriggerUpdate notifies the service to update the haproxy configuration
func (s *Service) TriggerUpdate() {
atomic.AddUint32(&s.changeCounter, 1)
}
// update the haproxy configuration
func (s *Service) updateHaproxy() error {
// Create a new config (in temp path)
config, tempConf, err := s.createConfigFile()
if err != nil {
return maskAny(err)
}
// If nothing has changed, no temp file is created, then do nothing
if tempConf == "" {
return nil
}
// Cleanup afterwards
defer os.Remove(tempConf)
// Validate the config
if err := s.validateConfig(tempConf, config); err != nil {
s.Logger.Errorf("haproxy config validation failed: %#v", err)
return maskAny(err)
}
// Move config to correct place
os.Remove(s.HaproxyConfPath)
if err := ioutil.WriteFile(s.HaproxyConfPath, []byte(config), confPerm); err != nil {
s.Logger.Errorf("Cannot copy haproxy config to %s: %#v", s.HaproxyConfPath, err)
return maskAny(err)
}
// Restart haproxy
if err := s.restartHaproxy(); err != nil {
return maskAny(err)
}
// Rember the current config
s.lastConfig = config
s.Logger.Infof("Restarted haproxy")
return nil
}
// createConfigFile creates a new haproxy configuration file.
// It returns the path of the new config file.
func (s *Service) createConfigFile() (string, string, error) {
// Fetch data from backend
services, err := s.Backend.Services()
if err != nil {
return "", "", maskAny(err)
}
// Extend with ACME info
services, err = s.AcmeService.Extend(services)
if err != nil {
return "", "", maskAny(err)
}
// Normalize services
for i, s := range services {
services[i] = s.Normalize()
}
// Sort the services
services.Sort()
// Render the content of the haproxy.cfg file
config, err := s.renderConfig(services)
if err != nil {
return "", "", maskAny(err)
}
// If nothing has changed, don't do anything
if s.lastConfig == config {
s.Logger.Debugf("Config has not changed")
return config, "", nil
}
// Log services
s.Logger.Infof("Found %d services", len(services))
for srvIndex, srv := range services {
s.Logger.Debugf("Service %d: %#v", srvIndex, srv)
}
// Create temp file first
tempFile, err := ioutil.TempFile("", "haproxy")
if err != nil {
return "", "", maskAny(err)
}
defer tempFile.Close()
if _, err := tempFile.WriteString(config); err != nil {
return "", "", maskAny(err)
}
return config, tempFile.Name(), nil
}
// validateConfig calls haproxy to validate the given config file.
func (s *Service) validateConfig(confPath, confContent string) error {
cmd := exec.Command(s.HaproxyPath, "-c", "-f", confPath)
output, err := cmd.CombinedOutput()
if err != nil {
s.Logger.Errorf("Error in haproxy config: %s", string(output))
fmt.Println()
fmt.Println(confContent)
fmt.Println()
return maskAny(err)
}
return nil
}
// restartHaproxy restarts haproxy, killing previous instances
func (s *Service) restartHaproxy() error {
args := []string{
"-f",
s.HaproxyConfPath,
}
lastPid := s.lastPid
if s.lastPid > 0 {
args = append(args, "-sf", strconv.Itoa(s.lastPid))
}
s.Logger.Debugf("Starting haproxy with %#v", args)
cmd := exec.Command(s.HaproxyPath, args...)
configureRestartHaproxyCmd(cmd)
cmd.Stdin = bytes.NewReader([]byte{})
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
s.Logger.Errorf("Failed to start haproxy: %#v", err)
return maskAny(err)
}
pid := -1
proc := cmd.Process
if proc != nil {
pid = proc.Pid
}
s.lastPid = pid
s.Logger.Debugf("haxproxy pid %d started", pid)
go func() {
// Wait for haproxy to terminate so we avoid defunct processes
if err := cmd.Wait(); err != nil {
s.Logger.Errorf("haproxy pid %d wait returned an error: %#v", pid, err)
} else {
s.Logger.Debugf("haproxy pid %d terminated", pid)
}
}()
if lastPid != 0 {
// Make sure the old haproxy terminates
go func() {
time.Sleep(time.Second * 10)
p, _ := os.FindProcess(lastPid)
if p != nil {
p.Kill()
}
}()
}
return nil
}
// close closes this service in a timely manor.
func (s *Service) close() {
// Interrupt the process when closing is requested twice.
if atomic.AddUint32(&s.signalCounter, 1) >= 2 {
s.exitProcess()
}
s.Logger.Infof("shutting down server in %s", osExitDelay.String())
time.Sleep(osExitDelay)
s.exitProcess()
}
// exitProcess terminates this process with exit code 1.
func (s *Service) exitProcess() {
s.Logger.Infof("shutting down server")
os.Exit(0)
}
// listenSignals waits for incoming OS signals and acts upon them
func (s *Service) listenSignals() {
// Set up channel on which to send signal notifications.
// We must use a buffered channel or risk missing the signal
// if we're not ready to receive when the signal is sent.
c := make(chan os.Signal, 2)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
// Block until a signal is received.
for {
select {
case sig := <-c:
s.Logger.Infof("server received signal %s", sig)
go s.close()
}
}
}