-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathendpoints.go
345 lines (307 loc) · 10.2 KB
/
endpoints.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
334
335
336
337
338
339
340
341
342
343
344
345
package nginx
import (
"context"
"errors"
"net/http"
"regexp"
"time"
// Packages
server "github.com/mutablelogic/go-server"
folders "github.com/mutablelogic/go-server/pkg/handler/nginx/folders"
router "github.com/mutablelogic/go-server/pkg/handler/router"
httprequest "github.com/mutablelogic/go-server/pkg/httprequest"
httpresponse "github.com/mutablelogic/go-server/pkg/httpresponse"
// Namespace imports
. "github.com/djthorpe/go-errors"
)
///////////////////////////////////////////////////////////////////////////////
// TYPES
type responseHealth struct {
Version string `json:"version"`
Uptime uint64 `json:"uptime"`
}
type responseTemplate struct {
Name string `json:"name,omitempty"`
Enabled *bool `json:"enabled,omitempty"` // Can be used for PATCH
Body string `json:"body,omitempty"` // Can be used for PATCH
}
///////////////////////////////////////////////////////////////////////////////
// TYPES
// Check interfaces are satisfied
var _ server.ServiceEndpoints = (*nginx)(nil)
///////////////////////////////////////////////////////////////////////////////
// GLOBALS
const (
jsonIndent = 2
)
var (
reRoot = regexp.MustCompile(`^/?$`)
reAction = regexp.MustCompile(`^/(test|reload|reopen)/?$`)
reListConfig = regexp.MustCompile(`^/config/?$`)
reConfig = regexp.MustCompile(`^/config/(.*)$`)
)
///////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS - ENDPOINTS
// Add endpoints to the router
func (service *nginx) AddEndpoints(ctx context.Context, r server.Router) {
// Path: /
// Methods: GET
// Scopes: read
// Description: Get nginx status (version, uptime, available and enabled configurations)
r.AddHandlerFuncRe(ctx, reRoot, service.GetHealth, http.MethodGet).(router.Route).
SetScope(service.ScopeRead()...)
// Path: /(test|reload|reopen)
// Methods: PUT
// Scopes: write
// Description: Test, reload and reopen nginx configuration
r.AddHandlerFuncRe(ctx, reAction, service.PutAction, http.MethodPut).(router.Route).
SetScope(service.ScopeWrite()...)
// Path: /config
// Methods: GET
// Scopes: read
// Description: Read the current set of configurations
r.AddHandlerFuncRe(ctx, reListConfig, service.ListConfig, http.MethodGet).(router.Route).
SetScope(service.ScopeRead()...)
// Path: /config
// Methods: POST
// Scopes: write
// Description: Create a new configuration
r.AddHandlerFuncRe(ctx, reListConfig, service.CreateConfig, http.MethodPost).(router.Route).
SetScope(service.ScopeWrite()...)
// Path: /config/{id}
// Methods: GET
// Scopes: read
// Description: Read a configuration
r.AddHandlerFuncRe(ctx, reConfig, service.ReadConfig, http.MethodGet).(router.Route).
SetScope(service.ScopeRead()...)
// Path: /config/{id}
// Methods: DELETE, POST, PATCH
// Scopes: write
// Description: Modify a configuration
r.AddHandlerFuncRe(ctx, reConfig, service.WriteConfig, http.MethodDelete, http.MethodPatch).(router.Route).
SetScope(service.ScopeWrite()...)
}
///////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
// Get nginx status
func (service *nginx) GetHealth(w http.ResponseWriter, r *http.Request) {
httpresponse.JSON(w, responseHealth{
Version: string(service.Version()),
Uptime: uint64(time.Since(service.run.Start).Seconds()),
}, http.StatusOK, jsonIndent)
}
// Do nginx action
func (service *nginx) PutAction(w http.ResponseWriter, r *http.Request) {
urlParameters := router.Params(r.Context())
switch urlParameters[0] {
case "test":
if err := service.Test(); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
}
case "reload":
if err := service.Reload(); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
}
case "reopen":
if err := service.Reopen(); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
}
default:
httpresponse.Error(w, http.StatusNotFound)
return
}
// Serve OK response with no body
httpresponse.Empty(w, http.StatusOK)
}
// List configurations
func (service *nginx) ListConfig(w http.ResponseWriter, r *http.Request) {
var result []responseTemplate
for _, tmpl := range service.folders.Templates() {
if response, err := service.tmplToResponse(tmpl); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
} else {
result = append(result, *response)
}
}
httpresponse.JSON(w, result, http.StatusOK, jsonIndent)
}
// Return a single configuration
func (service *nginx) ReadConfig(w http.ResponseWriter, r *http.Request) {
urlParameters := router.Params(r.Context())
tmpl := service.folders.Template(urlParameters[0])
if tmpl == nil {
httpresponse.Error(w, http.StatusNotFound)
return
} else if response, err := service.tmplToResponse(tmpl); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
} else {
httpresponse.JSON(w, response, http.StatusOK, jsonIndent)
}
}
// Create a new configuration
func (service *nginx) CreateConfig(w http.ResponseWriter, r *http.Request) {
var create responseTemplate
if err := httprequest.Body(&create, r); err != nil {
httpresponse.Error(w, http.StatusBadRequest, err.Error())
return
} else if create.Name == "" {
httpresponse.Error(w, http.StatusBadRequest, "Missing name")
return
} else if create.Body == "" {
httpresponse.Error(w, http.StatusBadRequest, "Missing body")
return
} else if tmpl := service.folders.Template(create.Name); tmpl != nil {
httpresponse.Error(w, http.StatusConflict)
return
}
// Create the configuration
if err := service.folders.Create(create.Name, []byte(create.Body)); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
}
// Check if we need to enable the configuration
if create.Enabled != nil && *create.Enabled {
if err := service.folders.Enable(create.Name); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
} else if err := service.Test(); err != nil {
// Rollback
err = errors.Join(err, service.folders.Delete(create.Name))
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
} else if err := service.Reload(); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
}
}
// Respond with the template
templ := service.folders.Template(create.Name)
if templ == nil {
httpresponse.Error(w, http.StatusNotFound, create.Name)
return
} else if response, err := service.tmplToResponse(templ); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
} else {
httpresponse.JSON(w, response, http.StatusOK, jsonIndent)
}
}
// PATCH or DELETE a configuration
func (service *nginx) WriteConfig(w http.ResponseWriter, r *http.Request) {
urlParameters := router.Params(r.Context())
templ := service.folders.Template(urlParameters[0])
if templ == nil {
httpresponse.Error(w, http.StatusNotFound)
return
}
switch r.Method {
case http.MethodDelete:
service.DeleteConfig(templ, w, r)
case http.MethodPatch:
service.PatchConfig(templ, w, r)
default:
httpresponse.Error(w, http.StatusMethodNotAllowed, r.Method)
}
}
// Delete a configuration
func (service *nginx) DeleteConfig(tmpl *folders.Template, w http.ResponseWriter, r *http.Request) {
// Disable the configuration
if tmpl.Enabled {
if err := service.folders.Disable(tmpl.Name); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
} else if err := service.Reload(); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
}
}
// Delete it
if err := service.folders.Delete(tmpl.Name); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
}
// Respond with no content
httpresponse.Empty(w, http.StatusOK)
}
// Update a configuration
func (service *nginx) PatchConfig(tmpl *folders.Template, w http.ResponseWriter, r *http.Request) {
var patch responseTemplate
var modified bool
if err := httprequest.Body(&patch, r); err != nil {
httpresponse.Error(w, http.StatusBadRequest, err.Error())
return
}
// Body - currently only disabled configurations can have their body changed TODO: change this
if patch.Body != "" {
if patch.Enabled != nil && tmpl.Enabled {
httpresponse.Error(w, http.StatusForbidden, "Cannot change body of enabled configuration")
return
}
if err := service.folders.Write(tmpl.Name, []byte(patch.Body)); err != nil && errors.Is(err, ErrNotModified) {
modified = false
} else if err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
} else {
// Force update
modified = true
patch.Enabled = &tmpl.Enabled
}
}
// Enabled
if patch.Enabled != nil {
modified = true
switch *patch.Enabled {
case true:
if !tmpl.Enabled {
if err := service.folders.Enable(tmpl.Name); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
}
}
if err := service.Test(); err != nil {
// Rollback
err = errors.Join(err, service.folders.Disable(tmpl.Name))
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
} else if err := service.Reload(); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
}
case false:
if tmpl.Enabled {
if err := service.folders.Disable(tmpl.Name); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
}
}
if err := service.Reload(); err != nil {
httpresponse.Error(w, http.StatusInternalServerError, err.Error())
return
}
}
}
// Return OK or Not Modified
if modified {
httpresponse.Empty(w, http.StatusOK)
} else {
httpresponse.Empty(w, http.StatusNotModified)
}
}
///////////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
func (service *nginx) tmplToResponse(tmpl *folders.Template) (*responseTemplate, error) {
if body, err := service.folders.Render(tmpl.Name); err != nil {
return nil, err
} else {
return &responseTemplate{
Name: tmpl.Name,
Enabled: &tmpl.Enabled,
Body: string(body),
}, nil
}
}