forked from Nitro/nginx-discovery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
225 lines (183 loc) · 5.53 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
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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"reflect"
"sort"
"text/template"
"time"
"github.com/Nitro/sidecar/service"
log "github.com/Sirupsen/logrus"
"github.com/kelseyhightower/envconfig"
"gopkg.in/relistan/rubberneck.v1"
)
const (
LoopDelayInterval = 3 * time.Second
)
type Config struct {
RefreshInterval time.Duration `envconfig:"REFRESH_INTERVAL" default:"5s"`
FollowService string `envconfig:"FOLLOW_SERVICE" default:"lazyraster"`
FollowPort int64 `envconfig:"FOLLOW_PORT" required:"true"`
TemplateFile string `envconfig:"TEMPLATE_FILENAME" default:"templates/nginx.conf.tmpl"`
UpdateCommand string `envconfig:"UPDATE_COMMAND"`
ValidateCommand string `envconfig:"VALIDATE_COMMAND"`
SidecarAddress string `envconfig:"SIDECAR_ADDRESS" required:"true"`
NginxConf string `envconfig:"NGINX_CONF" default:"/nginx/nginx.conf"`
NginxPID string `envconfig:"NGINX_PID" default:"/tmp/nginx.pid"`
}
type ApiServices struct {
Services map[string][]*service.Service
}
func WriteTemplate(config *Config, servers []string, output io.Writer) error {
funcMap := template.FuncMap{
"now": time.Now().UTC,
"servers": func() []string { return servers },
}
t, err := template.New("haproxy").Funcs(funcMap).ParseFiles(config.TemplateFile)
if err != nil {
return fmt.Errorf("Error parsing template '%s': %s", config.TemplateFile, err)
}
err = t.ExecuteTemplate(output, path.Base(config.TemplateFile), nil)
if err != nil {
return fmt.Errorf("Error executing template '%s': %s", config.TemplateFile, err)
}
return nil
}
// run executes a command and bubbles up the error.
func run(command string) error {
cmd := exec.Command("/bin/bash", "-c", command)
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
cmd.Stdout = stdout
cmd.Stderr = stderr
err := cmd.Run()
if err != nil {
err = fmt.Errorf("Error running '%s': %s\n%s\n%s", command, err, stdout, stderr)
}
return err
}
func innerUpdate(config *Config, previousServers []string) ([]string, error) {
servers, err := FetchServers(config)
if err != nil {
return nil, fmt.Errorf("Unable to fetch updated server list! (%s)", err)
}
if reflect.DeepEqual(servers, previousServers) {
return servers, nil
}
output, err := os.OpenFile(config.NginxConf, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return nil, fmt.Errorf("Unable to open output file for writing: %s", err)
}
// While this is not strictly necessary, it seems that O_TRUNC does not always work
err = output.Truncate(0)
if err != nil {
return nil, fmt.Errorf("Can't truncate file: %s", err)
}
err = WriteTemplate(config, servers, output)
if err != nil {
return nil, fmt.Errorf("Unable to write template: %s", err)
}
output.Close()
log.Info("Reloading Nginx config...")
err = run(config.ValidateCommand)
if err != nil {
return nil, fmt.Errorf("Unable to validate nginx config! (%s)", err)
}
if _, err := os.Stat(config.NginxPID); os.IsNotExist(err) {
log.Warn("Nginx is not running yet!")
return servers, nil
}
err = run(config.UpdateCommand)
if err != nil {
return nil, fmt.Errorf("Unable to reload nginx config! (%s)", err)
}
previousServers = servers
return servers, nil
}
func UpdateNginx(config *Config) {
var previousServers []string
var err error
for {
previousServers, err = innerUpdate(config, previousServers)
if err != nil {
log.Error(err)
}
time.Sleep(LoopDelayInterval)
}
}
func findPortWithSvcPortNumber(ports []service.Port, config *Config) string {
for _, port := range ports {
// Short circuit on the first port that matches
if port.ServicePort == config.FollowPort {
return fmt.Sprintf("%s:%d", port.IP, port.Port)
}
}
return ""
}
// FetchServers will connect to Sidecar, and with a timeout, fetch and
// parse the resulting structure. It will return a list of only the
// server:port combinations for the queried service
func FetchServers(config *Config) ([]string, error) {
client := &http.Client{Timeout: config.RefreshInterval * 2}
url := "http://" + config.SidecarAddress + "/api/services/" + config.FollowService + ".json"
resp, err := client.Get(url)
if err != nil {
return nil, err
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var apiServices ApiServices
err = json.Unmarshal(bytes, &apiServices)
if err != nil {
return nil, err
}
// We won't get here if there were no services, the Unmarshal should
// fail instead because we get an ApiError instead.
svcs := apiServices.Services[config.FollowService]
var servers []string
for _, svc := range svcs {
portStr := findPortWithSvcPortNumber(svc.Ports, config)
if len(portStr) < 1 {
log.Warnf("Got no port match for service on hostname: %s",
svc.Hostname,
)
continue
}
if svc.Status != 0 {
log.Debugf("Skipping service with status %d on hostname: %s",
svc.Status,
svc.Hostname,
)
continue
}
servers = append(servers, portStr)
}
// These need to be sorted for later comparison
sort.Strings(servers)
return servers, nil
}
func main() {
var config Config
err := envconfig.Process("discovery", &config)
if err != nil {
log.Fatal(err)
}
// Set some defaults that are unpleasant to put in the struct definition
if len(config.UpdateCommand) < 1 {
config.UpdateCommand = "/bin/kill -HUP `cat " + config.NginxPID + "`"
}
if len(config.ValidateCommand) < 1 {
config.ValidateCommand = "/nginx/nginx -t -c " + config.NginxConf
}
rubberneck.Print(config)
UpdateNginx(&config)
}