forked from CHESSComputing/CHAPaaS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
412 lines (377 loc) · 12.7 KB
/
handlers.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package main
// handlers module holds all HTTP handlers functions
//
// Copyright (c) 2023 - Valentin Kuznetsov <[email protected]>
//
import (
"errors"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/oauth2"
)
// HTTPError represents HTTP error record
type HTTPError struct {
Method string `json:"method"` // HTTP method
HTTPCode int `json:"http_code"` // HTTP error code
Code int `json:"code"` // server status code
Timestamp string `json:"timestamp"` // timestamp of the error
Path string `json:"path"` // URL path
UserAgent string `json:"user_agent"` // http user-agent field
XForwardedHost string `json:"x_forwarded_host"` // http.Request X-Forwarded-Host
XForwardedFor string `json:"x_forwarded_for"` // http.Request X-Forwarded-For
RemoteAddr string `json:"remote_addr"` // http.Request remote address
Reason string `json:"reason"` // error message
}
// HTTPResponse rpresents HTTP JSON response
type HTTPResponse struct {
Method string `json:"method"` // HTTP method
Path string `json:"path"` // URL path
UserAgent string `json:"user_agent"` // http user-agent field
XForwardedHost string `json:"x_forwarded_host"` // http.Request X-Forwarded-Host
XForwardedFor string `json:"x_forwarded_for"` // http.Request X-Forwarded-For
RemoteAddr string `json:"remote_addr"` // http.Request remote address
HTTPCode int `json:"http_code"` // HTTP error code
Code int `json:"code"` // server status code
Reason string `json:"reason"` // error code reason
Timestamp string `json:"timestamp"` // timestamp of the error
Response string `json:"response"` // response message
Error string `json:"error"` // error message
Data string `json:"data"` // HTTP response data
ElapsedTime string `json:"elapsed_time"` // elapsed time of HTTP request
}
// helper function to parse given template and return HTML page
func tmplPage(tmpl string, tmplData TmplRecord) string {
if tmplData == nil {
tmplData = make(TmplRecord)
}
var templates Templates
page := templates.Tmpl(tmpl, tmplData)
// tdir := fmt.Sprintf("%s/templates", Config.StaticDir)
// page := templates.TmplFile(tdir, tmpl, tmplData)
return page
}
// helper function to generate JSON response
func httpResponse(w http.ResponseWriter, r *http.Request, tmpl TmplRecord) {
httpCode := tmpl.GetInt("HttpCode")
tmpl["EndTime"] = time.Now().Unix()
elapsedTime := tmpl.GetElapsedTime()
tmpl["ElapsedTime"] = elapsedTime
// regenerate top part since we may
tmpl["Top"] = tmplPage("top.tmpl", tmpl)
top := tmpl.GetString("Top")
bottom := tmpl.GetString("Bottom")
tfile := tmpl.GetString("Template")
if tfile == "" {
if httpCode == 0 || httpCode == http.StatusOK {
tfile = "success.tmpl"
} else {
tfile = "error.tmpl"
}
}
page := tmplPage(tfile, tmpl)
if httpCode != 0 {
w.WriteHeader(httpCode)
}
w.Write([]byte(top + page + bottom))
}
// helper function to provide standard HTTP error reply
func httpError(w http.ResponseWriter, r *http.Request, tmpl TmplRecord, code int, err error, httpCode int) {
tmpl["Code"] = code
tmpl["Error"] = err
tmpl["HttpCode"] = httpCode
tmpl["Content"] = err.Error()
tmpl["Template"] = "error.tmpl"
httpResponse(w, r, tmpl)
}
// helper function to make initial template struct
func makeTmpl(title string) TmplRecord {
tmpl := make(TmplRecord)
tmpl["Title"] = title
tmpl["User"] = ""
tmpl["Base"] = Config.Base
tmpl["ServerInfo"] = info()
tmpl["Top"] = tmplPage("top.tmpl", tmpl)
tmpl["Bottom"] = tmplPage("bottom.tmpl", tmpl)
tmpl["StartTime"] = time.Now().Unix()
return tmpl
}
// gologinHandler provides wrapper for gologin handlers
// it gets HTTP request referrer and adds this information to oauth2 RedirectURL
func gologinHandler(config *oauth2.Config, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// get HTTP request referrer
referer := r.Referer()
if referer != "" && strings.Contains(referer, "redirect=") {
// modify oauth config RedirectURL with our referrer value
arr := strings.Split(referer, "redirect=")
api := arr[1]
config.RedirectURL = fmt.Sprintf("%s?redirect=%s", config.RedirectURL, api)
}
// Call the next handler
next.ServeHTTP(w, r)
})
}
// FaviconHandler
func FaviconHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, fmt.Sprintf("%s/images/favicon.ico", Config.StaticDir))
}
// helper function to check user's authorization
func checkAuthz(tmpl TmplRecord, w http.ResponseWriter, r *http.Request) error {
// get our session cookies
session, err := sessionStore.Get(r, sessionName)
if err != nil {
return err
}
// extract user context from OAuth
user, ok := session.GetOk(sessionUserName)
if !ok {
return errors.New("web session does not present user name")
}
token, ok := session.GetOk(sessionToken)
if !ok {
return errors.New("web session does not present access token")
}
provider, ok := session.GetOk(sessionProvider)
if !ok {
return errors.New("web session does not present access token")
}
tmpl["User"] = user
tmpl["Token"] = token
tmpl["Provider"] = provider
return nil
}
// helper function to get user name from web session
func getUser(r *http.Request) (string, error) {
// get our session cookies
session, err := sessionStore.Get(r, sessionName)
if err != nil {
return "", err
}
// extract user context from OAuth
user, ok := session.GetOk(sessionUserName)
if !ok {
return "", errors.New("web session does not present user name")
}
return fmt.Sprintf("%v", user), nil
}
// NotebookHandler handles login page
func NotebookHandler(w http.ResponseWriter, r *http.Request) {
tmpl := makeTmpl("CHAP notebook")
var userName string
var err error
// user HTTP call should present either valid token or it will be
// redirected to /login end-point
if err := checkAuthz(tmpl, w, r); err != nil {
rpath := fmt.Sprintf("%s/login?redirect=%s", Config.Base, r.URL.Path)
// get our session cookies
session, err := sessionStore.Get(r, sessionName)
if err != nil {
log.Printf("NotebookHandler, session %s redirect to %s due to error %v", sessionName, rpath, err)
http.Redirect(w, r, rpath, http.StatusTemporaryRedirect)
return
}
// check if ser has been authenticated with any OAuth providers
user, ok := session.GetOk(sessionUserName)
if !ok {
log.Printf("NotebookHandler, unable to identify username due to error %v", err)
http.Redirect(w, r, rpath, http.StatusTemporaryRedirect)
return
}
userID, _ := session.GetOk(sessionUserID)
provider, _ := session.GetOk(sessionProvider)
userName = user.(string)
tmpl["User"] = userName
tmpl["UserID"] = userID.(string)
tmpl["Provider"] = provider.(string)
} else {
userName, err = getUser(r)
if err != nil {
tmpl["Error"] = err
tmpl["HttpCode"] = http.StatusBadRequest
httpResponse(w, r, tmpl)
return
}
}
// we need to check if given notebook exists and if not we should create it
notebook := Notebook{
Host: Config.JupyterHost,
Token: Config.JupyterToken,
Root: Config.JupyterRoot,
User: userName,
FileName: "Untitled.ipynb",
}
if Config.Verbose > 0 {
log.Printf("Notebook %+v", notebook)
}
err = notebook.Create()
if err != nil {
tmpl["Error"] = err
tmpl["HttpCode"] = http.StatusInternalServerError
httpResponse(w, r, tmpl)
return
}
tmpl["JupyterToken"] = Config.JupyterToken
tmpl["JupyterHost"] = Config.JupyterHost
tmpl["Notebook"] = fmt.Sprintf("/users/%s/%s", userName, notebook.FileName)
tmpl["Template"] = "notebook.tmpl"
httpResponse(w, r, tmpl)
}
// ChapRunHandler handles login page
func ChapRunHandler(w http.ResponseWriter, r *http.Request) {
tmpl := makeTmpl("CHAP pipeline")
// get user name from web session
user, err := getUser(r)
if err != nil {
tmpl["Error"] = err
tmpl["HttpCode"] = http.StatusBadRequest
httpResponse(w, r, tmpl)
return
}
tmpl["Title"] = fmt.Sprintf("CHAP pipeline (%s)", user)
// prepare notebook
notebook := Notebook{
Host: Config.JupyterHost,
Token: Config.JupyterToken,
Root: Config.JupyterRoot,
User: user,
FileName: "Untitled.ipynb"}
tmpl["Notebook"] = notebook.FileName
// capture notebook content
rec, err := notebook.Capture()
if err != nil {
tmpl["Error"] = err
tmpl["HttpCode"] = http.StatusBadRequest
httpResponse(w, r, tmpl)
return
}
var lines []string
for _, cell := range rec.Content.Cells {
lines = append(lines, cell.Source)
}
if Config.Verbose > 0 {
log.Printf("### CHAP %+v, error %v", rec, err)
}
content := "CHAP pipeline<br/>"
// get reader, writer parameters
params, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
tmpl["Error"] = err
tmpl["HttpCode"] = http.StatusBadRequest
httpResponse(w, r, tmpl)
return
}
var reader, writer string
if values, ok := params["reader"]; ok {
reader = values[0]
}
if values, ok := params["writer"]; ok {
writer = values[0]
}
// TODO: think about how dynamically pass module and processor
// possibly via params to avoid hardcoding
module := "userprocessor"
processor := "UserProcessor"
// generate user code
genUserCode(user, module, processor, lines)
// generate user config
config := genChapConfig(user, module, reader, writer)
content += fmt.Sprintf("<pre>%s</pre><br/>", config)
// run CHAP pipeline
out, err := runCHAP(user, config)
tmpl["Template"] = "success.tmpl"
if err != nil {
tmpl["Error"] = err
tmpl["Template"] = "error.tmpl"
}
// prepare web response
userInput := strings.Trim(strings.Join(lines, "\n"), " ")
content += fmt.Sprintf("Input: <pre>%s</pre><br/>", userInput)
content += fmt.Sprintf("Output: <pre>%s</pre><br/>", out)
content += fmt.Sprintf("Error: <pre>%v</pre><br/>", err)
if Config.Verbose > 0 {
log.Println("### CHAP content\n", content)
}
tmpl["Content"] = template.HTML(content)
httpResponse(w, r, tmpl)
}
// ChapProfileHandler handles login page
func ChapProfileHandler(w http.ResponseWriter, r *http.Request) {
// TODO: need implementation to run CHAP in profile mode
// and then capture profile output and present it in graphical mode
ChapRunHandler(w, r)
}
// PublishHandler handles login page
func PublishHandler(w http.ResponseWriter, r *http.Request) {
// TODO: need implementation, should publish CHAP user workflow
// into user repository (separate from CHAP) and
// later include user workflow into list of supported workflows
// and publish new chap release to Galaxy
ChapRunHandler(w, r)
}
// WorkflowsHandler handles login page
func WorkflowsHandler(w http.ResponseWriter, r *http.Request) {
tmpl := makeTmpl("CHAP workflows")
// TODO: get list of workflows from user repository and
// present them on a web
workflows := getChapWorkflows()
tmpl["Workflows"] = workflows
tmpl["Template"] = "workflows.tmpl"
httpResponse(w, r, tmpl)
}
// LoginHandler handles login page
func LoginHandler(w http.ResponseWriter, r *http.Request) {
tmpl := makeTmpl("CHAP login")
tmpl["GithubLogin"] = fmt.Sprintf("%s/github/login", Config.Base)
tmpl["Template"] = "login.tmpl"
httpResponse(w, r, tmpl)
}
// AccessHandler handles login page
func AccessHandler(w http.ResponseWriter, r *http.Request) {
tmpl := makeTmpl("CHAP access")
// user HTTP call should present either valid token or it will be
// redirected to /login end-point
if err := checkAuthz(tmpl, w, r); err != nil {
tmpl["Error"] = err
tmpl["HttpCode"] = http.StatusBadRequest
httpResponse(w, r, tmpl)
return
}
user := tmpl.GetString("User")
token := tmpl.GetString("Token")
if Config.Verbose > 0 {
log.Printf("AccessHandler: user %s token %s", user, token)
}
// HTTP response with user info
content := fmt.Sprintf("User %s, access token: %s", user, token)
tmpl["Content"] = template.HTML(content)
tmpl["Template"] = "success.tmpl"
httpResponse(w, r, tmpl)
}
// DocsHandler handles status of CHAP server
func DocsHandler(w http.ResponseWriter, r *http.Request) {
tmpl := makeTmpl("CHAP documentation")
fname := fmt.Sprintf("%s/md/docs.md", Config.StaticDir)
content, err := mdToHTML(fname)
if err != nil {
httpError(w, r, tmpl, FileIOError, err, http.StatusInternalServerError)
return
}
tmpl["Content"] = template.HTML(content)
tmpl["Template"] = "docs.tmpl"
httpResponse(w, r, tmpl)
}
// IndexHandler handles status of CHAP server
func IndexHandler(w http.ResponseWriter, r *http.Request) {
tmpl := makeTmpl("CHAP as a Service")
tmpl["Base"] = Config.Base
tmpl["Token"] = ""
top := tmplPage("top.tmpl", tmpl)
bottom := tmplPage("bottom.tmpl", tmpl)
page := tmplPage("index.tmpl", tmpl)
w.Write([]byte(top + page + bottom))
}