This repository has been archived by the owner on Dec 26, 2023. It is now read-only.
/
web.go
394 lines (349 loc) · 11.6 KB
/
web.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package run
import (
"bytes"
"context"
"net/http"
"github.com/go-logr/logr"
"github.com/gorilla/mux"
"github.com/leg100/otf/internal"
"github.com/leg100/otf/internal/http/decode"
"github.com/leg100/otf/internal/http/html"
"github.com/leg100/otf/internal/http/html/paths"
"github.com/leg100/otf/internal/pubsub"
"github.com/leg100/otf/internal/rbac"
"github.com/leg100/otf/internal/resource"
"github.com/leg100/otf/internal/workspace"
)
type (
webHandlers struct {
html.Renderer
logger logr.Logger
runs webRunClient
workspaces webWorkspaceClient
}
webRunClient interface {
Create(ctx context.Context, workspaceID string, opts CreateOptions) (*Run, error)
List(ctx context.Context, opts ListOptions) (*resource.Page[*Run], error)
Get(ctx context.Context, id string) (*Run, error)
Delete(ctx context.Context, runID string) error
Cancel(ctx context.Context, runID string) error
ForceCancel(ctx context.Context, runID string) error
Apply(ctx context.Context, runID string) error
Discard(ctx context.Context, runID string) error
getLogs(ctx context.Context, runID string, phase internal.PhaseType) ([]byte, error)
watchWithOptions(ctx context.Context, opts WatchOptions) (<-chan pubsub.Event[*Run], error)
}
webWorkspaceClient interface {
Get(ctx context.Context, workspaceID string) (*workspace.Workspace, error)
GetPolicy(ctx context.Context, workspaceID string) (internal.WorkspacePolicy, error)
}
)
func (h *webHandlers) addHandlers(r *mux.Router) {
r = html.UIRouter(r)
r.HandleFunc("/workspaces/{workspace_id}/runs", h.list).Methods("GET")
r.HandleFunc("/workspaces/{workspace_id}/start-run", h.createRun).Methods("POST")
r.HandleFunc("/runs/{run_id}", h.get).Methods("GET")
r.HandleFunc("/runs/{run_id}/widget", h.getWidget).Methods("GET")
r.HandleFunc("/runs/{run_id}/delete", h.delete).Methods("POST")
r.HandleFunc("/runs/{run_id}/cancel", h.cancel).Methods("POST")
r.HandleFunc("/runs/{run_id}/force-cancel", h.forceCancel).Methods("POST")
r.HandleFunc("/runs/{run_id}/apply", h.apply).Methods("POST")
r.HandleFunc("/runs/{run_id}/discard", h.discard).Methods("POST")
r.HandleFunc("/runs/{run_id}/retry", h.retry).Methods("POST")
r.HandleFunc("/workspaces/{workspace_id}/watch", h.watch).Methods("GET")
// this handles the link the terraform CLI shows during a plan/apply.
r.HandleFunc("/{organization_name}/{workspace_id}/runs/{run_id}", h.get).Methods("GET")
}
func (h *webHandlers) createRun(w http.ResponseWriter, r *http.Request) {
var params struct {
WorkspaceID string `schema:"workspace_id,required"`
Operation Operation `schema:"operation,required"`
}
if err := decode.All(¶ms, r); err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
run, err := h.runs.Create(r.Context(), params.WorkspaceID, CreateOptions{
IsDestroy: internal.Bool(params.Operation == DestroyAllOperation),
PlanOnly: internal.Bool(params.Operation == PlanOnlyOperation),
Source: SourceUI,
})
if err != nil {
html.FlashError(w, err.Error())
http.Redirect(w, r, paths.Workspace(params.WorkspaceID), http.StatusFound)
return
}
http.Redirect(w, r, paths.Run(run.ID), http.StatusFound)
}
func (h *webHandlers) list(w http.ResponseWriter, r *http.Request) {
var params struct {
WorkspaceID string `schema:"workspace_id,required"`
PageNumber int `schema:"page[number]"`
}
if err := decode.All(¶ms, r); err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
ws, err := h.workspaces.Get(r.Context(), params.WorkspaceID)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
policy, err := h.workspaces.GetPolicy(r.Context(), ws.ID)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
runs, err := h.runs.List(r.Context(), ListOptions{
WorkspaceID: ¶ms.WorkspaceID,
PageOptions: resource.PageOptions{
PageNumber: params.PageNumber,
PageSize: html.PageSize,
},
})
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user, err := internal.SubjectFromContext(r.Context())
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response := struct {
workspace.WorkspacePage
*resource.Page[*Run]
CanUpdateWorkspace bool
}{
WorkspacePage: workspace.NewPage(r, "runs", ws),
Page: runs,
CanUpdateWorkspace: user.CanAccessWorkspace(rbac.UpdateWorkspaceAction, policy),
}
if isHTMX := r.Header.Get("HX-Request"); isHTMX == "true" {
if err := h.RenderTemplate("run_listing.tmpl", w, response); err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else {
h.Render("run_list.tmpl", w, response)
}
}
func (h *webHandlers) get(w http.ResponseWriter, r *http.Request) {
runID, err := decode.Param("run_id", r)
if err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
run, err := h.runs.Get(r.Context(), runID)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ws, err := h.workspaces.Get(r.Context(), run.WorkspaceID)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Get existing logs thus far received for each phase.
planLogs, err := h.runs.getLogs(r.Context(), run.ID, internal.PlanPhase)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
applyLogs, err := h.runs.getLogs(r.Context(), run.ID, internal.ApplyPhase)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
h.Render("run_get.tmpl", w, struct {
workspace.WorkspacePage
Run *Run
PlanLogs internal.Chunk
ApplyLogs internal.Chunk
}{
WorkspacePage: workspace.NewPage(r, run.ID, ws),
Run: run,
PlanLogs: internal.Chunk{Data: planLogs},
ApplyLogs: internal.Chunk{Data: applyLogs},
})
}
// getWidget renders a run "widget", i.e. the container that
// contains info about a run. Intended for use with an ajax request.
func (h *webHandlers) getWidget(w http.ResponseWriter, r *http.Request) {
runID, err := decode.Param("run_id", r)
if err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
run, err := h.runs.Get(r.Context(), runID)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := h.RenderTemplate("run_item.tmpl", w, run); err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (h *webHandlers) delete(w http.ResponseWriter, r *http.Request) {
runID, err := decode.Param("run_id", r)
if err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
run, err := h.runs.Get(r.Context(), runID)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = h.runs.Delete(r.Context(), runID)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, paths.Workspace(run.WorkspaceID), http.StatusFound)
}
func (h *webHandlers) cancel(w http.ResponseWriter, r *http.Request) {
runID, err := decode.Param("run_id", r)
if err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
if err := h.runs.Cancel(r.Context(), runID); err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, paths.Run(runID), http.StatusFound)
}
func (h *webHandlers) forceCancel(w http.ResponseWriter, r *http.Request) {
runID, err := decode.Param("run_id", r)
if err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
if err := h.runs.ForceCancel(r.Context(), runID); err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, paths.Run(runID), http.StatusFound)
}
func (h *webHandlers) apply(w http.ResponseWriter, r *http.Request) {
runID, err := decode.Param("run_id", r)
if err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
err = h.runs.Apply(r.Context(), runID)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, paths.Run(runID)+"#apply", http.StatusFound)
}
func (h *webHandlers) discard(w http.ResponseWriter, r *http.Request) {
runID, err := decode.Param("run_id", r)
if err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
err = h.runs.Discard(r.Context(), runID)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, paths.Run(runID), http.StatusFound)
}
func (h *webHandlers) retry(w http.ResponseWriter, r *http.Request) {
runID, err := decode.Param("run_id", r)
if err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
run, err := h.runs.Get(r.Context(), runID)
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
run, err = h.runs.Create(r.Context(), run.WorkspaceID, CreateOptions{
ConfigurationVersionID: &run.ConfigurationVersionID,
IsDestroy: &run.IsDestroy,
PlanOnly: &run.PlanOnly,
Source: SourceUI,
})
if err != nil {
html.FlashError(w, err.Error())
http.Redirect(w, r, paths.Run(runID), http.StatusFound)
return
}
http.Redirect(w, r, paths.Run(run.ID), http.StatusFound)
}
func (h *webHandlers) watch(w http.ResponseWriter, r *http.Request) {
var params struct {
WorkspaceID string `schema:"workspace_id,required"`
Latest bool `schema:"latest"`
RunID string `schema:"run_id"`
}
if err := decode.All(¶ms, r); err != nil {
h.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
events, err := h.runs.watchWithOptions(r.Context(), WatchOptions{
WorkspaceID: internal.String(params.WorkspaceID),
})
if err != nil {
h.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
rc := http.NewResponseController(w)
rc.Flush()
for {
select {
case <-r.Context().Done():
return
case event, ok := <-events:
if !ok {
return
}
// Handle query parameters which filter run events:
// - 'latest' specifies that the client is only interest in events
// relating to the latest run for the workspace
// - 'run-id' (mutually exclusive with 'latest') - specifies
// that the client is only interested in events relating to that
// run.
// - otherwise, if neither of those parameters are specified
// then events for all runs are relayed.
if params.Latest && !event.Payload.Latest {
// skip: run is not the latest run for a workspace
continue
} else if params.RunID != "" && params.RunID != event.Payload.ID {
// skip: event is for a run which does not match the
// filter
continue
}
//
// render HTML snippet and send as payload in SSE events
//
itemHTML := new(bytes.Buffer)
if err := h.RenderTemplate("run_item.tmpl", itemHTML, event.Payload); err != nil {
h.logger.Error(err, "rendering template for run item")
continue
}
if event.Type == pubsub.CreatedEvent {
// newly created run is sent with "created" event type
pubsub.WriteSSEEvent(w, itemHTML.Bytes(), event.Type, false)
} else {
// updated run events target existing run items in page
pubsub.WriteSSEEvent(w, itemHTML.Bytes(), pubsub.EventType("run-item-"+event.Payload.ID), false)
}
if params.Latest {
// also write a 'latest-run' event if the caller has requested
// the latest run for the workspace
pubsub.WriteSSEEvent(w, itemHTML.Bytes(), "latest-run", false)
}
rc.Flush()
}
}
}