-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathroutes.go
355 lines (339 loc) · 8.44 KB
/
routes.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
package main
import (
"crypto/tls"
"io"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
"github.com/gin-gonic/gin"
"github.com/perlogix/dama/data"
"github.com/yhat/wsutil"
)
// User struct is to read JSON values into struct to create new users
type User struct {
Username string `json:"username"`
Token string `json:"token"`
Role string `json:"role"`
}
// api route is proxy requests to the right container based on name http param
func api(c *gin.Context) {
name := c.Param("name")
key := strings.Split(name, "/")[1]
var api string
if dpAPI, _ := db.HGet("deployedPort", key).Result(); dpAPI != "" {
api = "localhost:" + dpAPI
}
if api == "" {
if sbAPI, _ := db.HGet("sandboxPort", key).Result(); sbAPI != "" {
api = "localhost:" + sbAPI
}
}
if api == "" {
c.String(400, "API not found")
return
}
backendURL := &url.URL{Scheme: "http", Host: api}
p := httputil.NewSingleHostReverseProxy(backendURL)
var pathRewrite string
pathRewrite = strings.TrimPrefix(c.Request.URL.Path, "/api/"+key)
if pathRewrite == "" {
pathRewrite = "/"
}
c.Request.URL.Path = pathRewrite
p.ServeHTTP(c.Writer, c.Request)
}
//TODO: Make POST
// expire route is to increate the expire value for a user. Default expire from config.yml is set.
func expire(c *gin.Context) {
user := c.Query("user")
expire := c.Query("expire")
if expire == "" || user == "" {
c.String(400, "Bad request")
return
}
if exp, _ := db.HGet(user, "expire").Result(); exp != "" {
db.HSet(user, "expire", expire)
c.String(201, "Updated expire")
}
}
// createUser route is used to create a new user into Redis DB
func createUser(c *gin.Context) {
usr := &User{}
if err := c.Bind(usr); err != nil {
c.String(500, err.Error())
return
}
if exist, _ := db.HGet("accounts", usr.Username).Result(); exist != "" {
c.String(400, "User already in DB")
return
}
user := map[string]interface{}{
"key": usr.Token,
"sandbox": genToken(),
"deployed": genToken(),
"expire": DamaConfig.Expire,
"role": usr.Role,
}
accounts := map[string]interface{}{
usr.Username: usr.Token,
}
var err error
_, err = db.HMSet("accounts", accounts).Result()
if err != nil {
c.String(500, "Error adding to accounts")
return
}
_, err = db.HMSet(usr.Username, user).Result()
if err != nil {
c.String(500, "Error adding user")
return
}
db.BgSave()
getAccounts()
c.String(201, "Created")
}
// getAPI route is used to retrieve keys for sandbox and deploy APIs
func getAPI(c *gin.Context) {
name := c.MustGet(gin.AuthUserKey).(string)
deployAPI, _ := db.HGet(name, "deployed").Result()
sandAPI, _ := db.HGet(name, "sandbox").Result()
if deployAPI != "" && sandAPI != "" {
c.String(200, deployAPI+":"+sandAPI)
return
}
c.String(404, "")
}
// ws route is used to proxy ws & wss to the correct running gotty docker container
func ws(c *gin.Context) {
name := c.MustGet(gin.AuthUserKey).(string)
file := c.Request.Header.Get("File")
new := c.Request.Header.Get("New")
image := c.Request.Header.Get("Image")
port := c.Request.Header.Get("Port")
var wsPort string
var backend string
if new != "" {
deleteContainers(name, "build")
}
wsPort, _ = db.HGet("wsPort", name).Result()
if new == "" && wsPort != "" {
backend = "localhost:" + wsPort
} else {
ctr, err := createContainer(name, image, file, port, false)
if err != nil {
c.String(500, err.Error())
return
}
sbAPI, _ := db.HGet(name, "sandbox").Result()
db.HSet("sandboxPort", sbAPI, strings.Split(ctr, ":")[1])
wsPort = strings.Split(ctr, ":")[0]
db.HSet("wsPort", name, wsPort)
backend = "localhost:" + wsPort
}
var scheme string
if DamaConfig.Gotty.TLS {
scheme = "wss"
} else {
scheme = "ws"
}
backendURL := &url.URL{Scheme: scheme, Host: backend}
p := wsutil.NewSingleHostReverseProxy(backendURL)
p.TLSClientConfig = &tls.Config{InsecureSkipVerify: DamaConfig.HTTPS.VerifyTLS}
p.ServeHTTP(c.Writer, c.Request)
}
// deploy route is called when user requests a new deploy from their dama.yml
func deploy(c *gin.Context) {
name := c.MustGet(gin.AuthUserKey).(string)
df := &data.Damafile{}
if err := c.Bind(df); err != nil {
c.String(500, err.Error())
return
}
if df.Image != "" && !checkImg(df.Image) {
c.String(404, df.Image+" Image not found")
return
}
path := pwd + "/upload/" + name
err := os.MkdirAll(path, 0755)
if err != nil {
c.String(500, err.Error())
return
}
t := template.New("tmpl")
t, _ = t.Parse(tmpl)
f, _ := os.Create(path + "/.dama")
err = os.Chmod(path+"/.dama", 0755)
if err != nil {
c.String(500, err.Error())
return
}
err = t.Execute(f, df)
if err != nil {
c.String(500, err.Error())
return
}
f.Close()
if df.Env != nil {
var envs = make(map[string]interface{})
for _, e := range df.Env {
split := strings.Split(e, "=")
envs[split[0]] = split[1]
}
db.HMSet(name+"_env", envs)
}
file := path + "/.dama"
image := df.Image
var port string
if df.Port == "" {
port = "5000"
} else {
port = df.Port
}
var ctr string
ctr, err = createContainer(name, image, file, port, true)
if err != nil {
c.String(500, err.Error())
return
}
deployed, _ := db.HGet(name, "deployed").Result()
db.HSet("deployedPort", deployed, strings.Split(ctr, ":")[1])
c.String(201, deployed)
}
// uploads route is for uploading files to the users workspace directory
func uploads(c *gin.Context) {
name := c.MustGet(gin.AuthUserKey).(string)
err := c.Request.ParseMultipartForm(32 << 20)
if err != nil {
c.String(500, err.Error())
return
}
path := pwd + "/upload/" + name
pathSize, err := dirSize(path)
if err != nil {
c.String(500, err.Error())
return
}
if pathSize >= int64(DamaConfig.UploadSize) {
c.String(500, "Workspace size limit reached")
return
}
info, handler, err := c.Request.FormFile("uploadfile")
if err != nil {
c.String(500, err.Error())
return
}
defer info.Close()
file := path + "/" + filepath.Base(handler.Filename)
out, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE, 0640)
if err != nil {
c.String(500, err.Error())
return
}
defer out.Close()
_, err = io.Copy(out, info)
if err != nil {
c.String(500, err.Error())
return
}
c.String(201, "Uploaded")
}
// download route is for downloading files from workspace directory
func download(c *gin.Context) {
name := c.MustGet(gin.AuthUserKey).(string)
file := c.Query("file")
if file == "" {
c.String(500, "No file specified")
return
}
path := pwd + "/upload/" + name + "/" + file
_, err := os.Stat(path)
if os.IsNotExist(err) {
c.String(500, err.Error())
return
}
c.File(path)
}
// envs route is for setting environment variables for running docker containers
func envs(c *gin.Context) {
name := c.MustGet(gin.AuthUserKey).(string)
env := &data.Damafile{}
if err := c.Bind(env); err != nil {
c.String(500, err.Error())
return
}
if env.Env == nil {
c.String(400, "No environment settings")
return
}
for _, e := range env.Env {
if match, err := regexp.MatchString("\\w*=\\w*", e); !match {
if err != nil {
c.String(500, err.Error())
}
c.String(500, "Environment setting needs to be key=value")
return
}
}
envs, _ := db.HGetAll(name + "_env").Result()
totalMapLen := len(env.Env) + len(envs)
if totalMapLen < DamaConfig.EnvSize {
var envs = make(map[string]interface{})
for _, e := range env.Env {
split := strings.Split(e, "=")
envs[split[0]] = split[1]
}
db.HMSet(name+"_env", envs)
c.String(201, "Created")
return
}
c.String(500, "Reached max amount of env tags, max is 20")
}
// create route is called when creating a new on-demand or sandbox container
func create(c *gin.Context) {
name := c.MustGet(gin.AuthUserKey).(string)
df := &data.Damafile{}
if err := c.Bind(df); err != nil {
c.String(500, err.Error())
return
}
if df.Image != "" && !checkImg(df.Image) {
c.String(404, df.Image+" Image not found")
return
}
path := pwd + "/upload/" + name
err := os.MkdirAll(path, 0755)
if err != nil {
c.String(500, err.Error())
return
}
t := template.New("tmpl")
t, _ = t.Parse(tmpl)
f, _ := os.Create(path + "/.dama")
err = os.Chmod(path+"/.dama", 0755)
if err != nil {
c.String(500, err.Error())
return
}
err = t.Execute(f, df)
if err != nil {
c.String(500, err.Error())
return
}
err = f.Close()
if err != nil {
c.String(500, err.Error())
}
if df.Env != nil {
var envs = make(map[string]interface{})
for _, e := range df.Env {
split := strings.Split(e, "=")
envs[split[0]] = split[1]
}
db.HMSet(name+"_env", envs)
}
c.String(201, "OK")
}