-
Notifications
You must be signed in to change notification settings - Fork 5
/
updater.go
304 lines (250 loc) · 7.12 KB
/
updater.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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"text/template"
)
var Version = "N/D"
type Application struct {
ConfigFile string
Config *NginxConfig
NoSaveConfig bool
TemplateName string
Template *template.Template
OutputFile string
NoReload bool
}
func (app *Application) Setup() error {
var err error
app.Template, err = template.ParseFiles(app.TemplateName)
if err != nil {
return err
}
app.Config = NewNginxConfig()
// try to load config from file
if app.ConfigFile != "" {
log.Printf("Trying to load config from %q", app.ConfigFile)
if err := app.Config.Load(app.ConfigFile); err != nil {
log.Printf("Couldn't load config from file. Using an empty config.")
log.Print(err)
// force reset config because we don't know what JSONDecoder has done to the original one
app.Config = NewNginxConfig()
}
}
return app.reconfigureNginx()
}
func (app *Application) reconfigureNginx() error {
// try to save config to file
if app.ConfigFile != "" && !app.NoSaveConfig {
log.Printf("Trying to save config to %q", app.ConfigFile)
if err := app.Config.Save(app.ConfigFile); err != nil {
log.Printf("Couldn't save config to file. Skipping.")
log.Print(err)
}
}
// render template
f, err := os.Create(app.OutputFile)
if err != nil {
return err
}
defer f.Close()
app.Template.Execute(f, app.Config)
// reload nginx
if !app.NoReload {
return exec.Command("nginx", "-s", "reload").Run()
}
return nil
}
func (app *Application) DeleteServer(w http.ResponseWriter, r *http.Request) {
serverId := r.FormValue("id")
if serverId == "" {
http_err(w, "Server identifier is not specified", nil)
return
}
// delete config from map
delete(app.Config.ServerConfigs, serverId)
// reconfigure nginx
if err := app.reconfigureNginx(); err != nil {
http_err(w, "Could not reconfigure nginx", err)
return
}
}
func (app *Application) UpdateServer(w http.ResponseWriter, r *http.Request) {
var config ServerConfig
defer r.Body.Close()
err := json.NewDecoder(r.Body).Decode(&config)
if err != nil {
http_err(w, "Data parsing error", err)
return
}
// validate config id
if config.Id == "" {
http_err(w, "Server identifier is not specified", err)
return
}
// add/update config to map
app.Config.ServerConfigs[config.Id] = &config
// reconfigure nginx
if err := app.reconfigureNginx(); err != nil {
http_err(w, "Could not reconfigure nginx", err)
return
}
}
func (app *Application) DeleteUpstream(w http.ResponseWriter, r *http.Request) {
upstreamId := r.FormValue("id")
if upstreamId == "" {
http_err(w, "Upstream identifier is not specified", nil)
return
}
// delete upstream from map
delete(app.Config.UpstreamConfigs, upstreamId)
// reconfigure nginx
if err := app.reconfigureNginx(); err != nil {
http_err(w, "Could not reconfigure nginx", err)
return
}
}
func (app *Application) UpdateUpstream(w http.ResponseWriter, r *http.Request) {
var upstream UpstreamConfig
// get input
defer r.Body.Close()
err := json.NewDecoder(r.Body).Decode(&upstream)
if err != nil {
http_err(w, "Data parsing error", err)
return
}
// validate input
if upstream.Id == "" {
http_err(w, "Upstream identifier is not specified", err)
return
}
// update config
app.Config.UpstreamConfigs[upstream.Id] = &upstream
// reconfigureNginx
if err := app.reconfigureNginx(); err != nil {
http_err(w, "Could not reconfigure nginx", err)
}
}
func (app *Application) AddUpstreamServer(w http.ResponseWriter, r *http.Request) {
var data struct {
UpstreamId string `json:"upstream_id"`
ServerURL string `json:"server_url"`
}
// get input data
defer r.Body.Close()
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
http_err(w, "Data parsing error", err)
return
}
// validate input
if data.UpstreamId == "" {
http_err(w, "Upstream identifier is not specified", err)
return
}
// update config with the new upstream
upstream, ok := app.Config.UpstreamConfigs[data.UpstreamId]
if !ok {
http_err(w, fmt.Sprintf("Upstream not found: %q", data.UpstreamId), nil)
return
}
// add upstream
duplicateFound := false
for _, s := range upstream.Servers {
if s == data.ServerURL {
duplicateFound = true
break
}
}
if !duplicateFound {
upstream.Servers = append(upstream.Servers, data.ServerURL)
}
// reconfigure nginx
if err := app.reconfigureNginx(); err != nil {
http_err(w, "Could not reconfigure nginx", err)
return
}
}
func (app *Application) DeleteUpstreamServer(w http.ResponseWriter, r *http.Request) {
var data struct {
UpstreamId string `json:"upstream_id"`
ServerURL string `json:"server_url"`
}
// get input data
defer r.Body.Close()
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
http_err(w, "Data parsing error", err)
return
}
// validate config id
if data.UpstreamId == "" {
http_err(w, "Upstream identifier is not specified", err)
return
}
// get upstream
upstream, ok := app.Config.UpstreamConfigs[data.UpstreamId]
if !ok {
http_err(w, fmt.Sprintf("Upstream not found: %q", data.UpstreamId), nil)
return
}
// check for empty upstream
if len(upstream.Servers) <= 0 {
http_err(w, fmt.Sprintf("Trying to delete from empty upstream: %q", data.UpstreamId), nil)
return
}
// delete upstream
// we assume that new array will contain (n-1) elements; so capacity=n-1
newServers := make([]string, 0, len(upstream.Servers)-1)
for _, s := range upstream.Servers {
if s != data.ServerURL {
newServers = append(newServers, s)
}
}
upstream.Servers = newServers
// reconfigure nginx
if err := app.reconfigureNginx(); err != nil {
http_err(w, "Could not reconfigure nginx", err)
return
}
}
func main() {
var err error
app := Application{}
var doShowVersion bool
var listenTo string
flag.BoolVar(&doShowVersion, "version", false, "Show application version and exit")
flag.StringVar(&app.TemplateName, "template", "default.conf.tmpl", "Config file template to be rendered. Default: default.conf.tmpl")
flag.StringVar(&app.OutputFile, "out", "/etc/nginx/conf.d/default.conf", "Path to the config file to be updated. Default: /etc/nginx/conf.d/default.conf")
flag.StringVar(&app.ConfigFile, "config", "", "Path to the config file. Default: empty")
flag.BoolVar(&app.NoSaveConfig, "no-save-config", false, "Don't save (overwrite existing) config file. Default: false")
flag.StringVar(&listenTo, "listen", ":3456", "Host and port to listen to. Default: :3456")
flag.BoolVar(&app.NoReload, "no-reload", false, "Don't reload Nginx when applying changes. Default: false")
flag.Parse()
if doShowVersion {
fmt.Println(Version)
return
}
// initialize app
err = app.Setup()
if err != nil {
log.Fatal(err)
}
// server configs
http.HandleFunc("/updateServer", app.UpdateServer)
http.HandleFunc("/deleteServer", app.DeleteServer)
// upstreams
http.HandleFunc("/updateUpstream", app.UpdateUpstream)
http.HandleFunc("/deleteUpstream", app.DeleteUpstream)
http.HandleFunc("/addUpstreamServer", app.AddUpstreamServer)
http.HandleFunc("/deleteUpstreamServer", app.DeleteUpstreamServer)
err = http.ListenAndServe(listenTo, nil)
if err != nil {
log.Fatal(err)
}
}