-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
576 lines (478 loc) · 13.6 KB
/
main.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
package main
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"regexp"
"strings"
"sync"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-playground/webhooks/v6/github"
"github.com/go-playground/webhooks/v6/gitlab"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/proxy"
"github.com/samber/lo"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
"golang.org/x/crypto/acme/autocert"
)
type TemplateConfig struct {
Name string `toml:"name" json:"name"`
MatchDependencies []string `toml:"match_dependencies" json:"match_dependencies"`
Info string `toml:"info" json:"info"`
Build StepBuild `toml:"build" json:"build"`
Run StepRun `toml:"run" json:"run"`
}
type DeployStep struct {
Image string `toml:"image" json:"image"`
Script string `toml:"script" json:"script"`
}
type StepBuild struct {
DeployStep
Artifact string `toml:"artifact"`
}
type StepRun struct {
DeployStep
Port string `toml:"port"`
}
// Globals
var deploymentTemplates map[string]TemplateConfig
var apps []*App
// CLI Flags
var domain string
var ssl bool
var debug bool
var port string
var sslPort string
func writeConfig() {
data, err := json.MarshalIndent(apps, "", " ")
if err != nil {
log.Fatal(err)
}
err = os.WriteFile("./apps.json", data, 0644)
if err != nil {
log.Fatal(err)
}
}
func main() {
// Save config on exit
defer func() {
writeConfig()
}()
// Handle CLI
flag.StringVar(&domain, "domain", "", "Base domain for all deployments and UI")
flag.BoolVar(&ssl, "ssl", false, "Enable SSL")
flag.BoolVar(&debug, "debug", false, "Enable debug mode")
flag.StringVar(&port, "port", "80", "Port for HTTP")
flag.StringVar(&sslPort, "ssl-port", "443", "Port for HTTPS")
flag.Parse()
if domain == "" {
log.Fatal("-domain is required")
}
// Load config
if _, err := os.Stat("./apps.json"); !os.IsNotExist(err) {
data, err := os.ReadFile("./apps.json")
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(data, &apps)
if err != nil {
log.Fatal(err)
}
}
// Recreate pointer references for app and deployment
for _, app := range apps {
for _, deployment := range app.Deployments {
deployment.App = app
deployment.RequestsLogLock = &sync.Mutex{}
if deployment.BuildJob != nil {
deployment.BuildJob.Deployment = deployment
}
}
}
// Init
loadTemplates()
connectDocker()
// Create required tmp folder structure
if err := createDirIfNotExists("./mounts"); err != nil {
log.Fatal(err)
}
if err := createDirIfNotExists("./mounts/build"); err != nil {
log.Fatal(err)
}
if err := createDirIfNotExists("./mounts/running"); err != nil {
log.Fatal(err)
}
if err := createDirIfNotExists("./artifacts"); err != nil {
log.Fatal(err)
}
// Initialize web server
proxy.WithClient(&fasthttp.Client{
NoDefaultUserAgentHeader: true,
DisablePathNormalizing: true,
})
app := fiber.New(
fiber.Config{
DisableStartupMessage: true,
},
)
app.Get("/runner/api/info", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"templates": deploymentTemplates,
// Unused for now:
"domain": domain,
"ssl": ssl,
"debug": debug,
"port": port,
"sslPort": sslPort,
})
})
app.Get("/runner/api/app", func(c *fiber.Ctx) error {
return c.JSON(apps)
})
app.Get("/runner/api/app/:id", func(c *fiber.Ctx) error {
id := c.Params("id", "")
if id == "" {
return fiber.NewError(fiber.StatusBadRequest, "Invalid app id")
}
app := getAppById(id)
if app == nil {
return fiber.NewError(fiber.StatusBadRequest, "Unkown app id")
}
return c.JSON(app)
})
app.Post("/runner/api/app", func(c *fiber.Ctx) error {
var body struct {
Name string `json:"name"`
TemplateId string `json:"template_id"`
GitUrl string `json:"git_url"`
GitUsername *string `json:"git_username,omitempty"`
GitPassword *string `json:"git_password,omitempty"`
Env string `json:"env"`
PackageManager string `json:"package_manager"`
}
if err := c.BodyParser(&body); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
if body.Name == "" || body.TemplateId == "" || body.GitUrl == "" {
return fiber.NewError(fiber.StatusBadRequest, "Missing required fields")
}
app := App{
Id: makeId(),
Name: body.Name,
TemplateId: &body.TemplateId,
GitUrl: body.GitUrl,
GitUsername: body.GitUsername,
GitPassword: body.GitPassword,
Env: ptr(body.Env),
WebhookSecret: makeId(),
PackageManager: body.PackageManager,
}
apps = append(apps, &app)
writeConfig()
return c.JSON(app)
})
app.Post("/runner/api/app/:id/env", func(c *fiber.Ctx) error {
id := c.Params("id", "")
if id == "" {
return fiber.NewError(fiber.StatusBadRequest, "Invalid app id")
}
app := getAppById(id)
if app == nil {
return fiber.NewError(fiber.StatusBadRequest, "Unkown app id")
}
var body struct {
Env string `json:"env"`
}
if err := c.BodyParser(&body); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
if body.Env == "" {
return fiber.NewError(fiber.StatusBadRequest, "Missing required fields")
}
app.Env = ptr(body.Env)
writeConfig()
return c.JSON(fiber.Map{
"success": true,
})
})
app.Delete("/runner/api/app/:id", func(c *fiber.Ctx) error {
id := c.Params("id", "")
if id == "" {
return fiber.NewError(fiber.StatusBadRequest, "Invalid app id")
}
app := getAppById(id)
if app == nil {
return fiber.NewError(fiber.StatusBadRequest, "Unkown app id")
}
// Delete app
apps = lo.Filter(apps, func(a *App, i int) bool {
return a.Id != id
})
// Delete deployments
for _, deployment := range app.Deployments {
if deployment.ContainerId != nil {
dockerStop(*deployment.ContainerId)
dockerRemove(*deployment.ContainerId)
}
}
writeConfig()
return c.JSON(fiber.Map{
"success": true,
})
})
app.Post("/runner/api/app/:id/deploy", func(c *fiber.Ctx) error {
id := c.Params("id", "")
if id == "" {
return fiber.NewError(fiber.StatusBadRequest, "Invalid app id")
}
var body struct {
Branch string `json:"branch"`
Commit string `json:"commit"`
}
if err := c.BodyParser(&body); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
if body.Branch == "" || body.Commit == "" {
return fiber.NewError(fiber.StatusBadRequest, "Missing required fields")
}
app := getAppById(id)
if app == nil {
return fiber.NewError(fiber.StatusBadRequest, "Unkown app id")
}
deployment, err := app.Deploy(body.Branch, body.Commit)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
return c.JSON(deployment)
})
app.Delete("/runner/api/deployment/:id", func(c *fiber.Ctx) error {
id := c.Params("id", "")
if id == "" {
return fiber.NewError(fiber.StatusBadRequest, "Invalid deployment id")
}
deployment := getDeploymentById(id)
if deployment == nil {
return fiber.NewError(fiber.StatusBadRequest, "Unkown deployment id")
}
// Delete deployment
deployment.App.Deployments = lo.Filter(
deployment.App.Deployments,
func(d *Deployment, i int) bool {
return d.Id != id
},
)
if deployment.ContainerId != nil {
dockerStop(*deployment.ContainerId)
dockerRemove(*deployment.ContainerId)
}
writeConfig()
return c.JSON(fiber.Map{
"success": true,
})
})
app.Get("/runner/api/deployment/:id/logs/:logType", func(c *fiber.Ctx) error {
id := c.Params("id", "")
if id == "" {
return fiber.NewError(fiber.StatusBadRequest, "Invalid deployment id")
}
logType := c.Params("logType", "")
deployment := getDeploymentById(id)
if deployment == nil {
return fiber.NewError(fiber.StatusBadRequest, "Unkown deployment id")
}
if deployment.BuildJob == nil {
return fiber.NewError(fiber.StatusBadRequest, "No build job found")
}
var err error
var logs string
switch logType {
case "build":
logs, err = deployment.BuildJob.GetLogs()
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
case "running":
logs, err = deployment.GetLogs()
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
case "requests":
logs = strings.Join(deployment.RequestsLog, "\n")
default:
return fiber.NewError(fiber.StatusBadRequest, "Invalid log type")
}
var deploymentUrl string
if deployment.Status == "Running" {
deploymentUrl = deployment.GetUrl()
}
return c.JSON(fiber.Map{
"logs": logs,
"build_status": deployment.BuildJob.Status,
"url": deploymentUrl,
})
})
app.Post("/runner/api/app/:id/webhook/:provider", func(c *fiber.Ctx) error {
id := c.Params("id", "")
if id == "" {
return fiber.NewError(fiber.StatusBadRequest, "Invalid app id")
}
app := getAppById(id)
if app == nil {
return fiber.NewError(fiber.StatusBadRequest, "Unkown app id")
}
provider := c.Params("provider", "")
var r http.Request
err := fasthttpadaptor.ConvertRequest(c.Context(), &r, true)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
var commit, branch string
switch provider {
case "github":
githubHook, _ := github.New(github.Options.Secret(app.WebhookSecret))
payload, err := githubHook.Parse(&r, github.PushEvent)
if err != nil {
if err == github.ErrEventNotFound {
return fiber.NewError(fiber.StatusBadRequest, "Invalid event")
} else {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
}
switch payload.(type) {
case github.PushPayload:
push := payload.(github.PushPayload)
commit = push.After
branch = plumbing.ReferenceName(push.Ref).Short()
}
case "gitlab":
gitlabHook, _ := gitlab.New(gitlab.Options.Secret(app.WebhookSecret))
payload, err := gitlabHook.Parse(&r, gitlab.PushEvents)
if err != nil {
if err == gitlab.ErrEventNotFound {
return fiber.NewError(fiber.StatusBadRequest, "Invalid event")
} else {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
}
switch payload.(type) {
case gitlab.PushEventPayload:
push := payload.(gitlab.PushEventPayload)
commit = push.After
branch = plumbing.ReferenceName(push.Ref).Short()
}
default:
return fiber.NewError(fiber.StatusBadRequest, "Invalid provider type")
}
go func() {
_, err := app.Deploy(branch, commit)
if err != nil {
log.Println(err)
}
}()
return c.JSON(fiber.Map{
"success": true,
})
})
// Serve Vue Frontend
app.Static("/runner", "./www/dist/")
app.Get("/runner/*", func(ctx *fiber.Ctx) error {
return ctx.SendFile("./www/dist/index.html", true)
})
app.Use(func(c *fiber.Ctx) error {
// Redirect to control panel
if c.Hostname() == domain && bytes.Equal(c.Request().URI().Path(), []byte("/")) {
return c.Redirect("/runner/")
}
// Skip acme
if bytes.HasPrefix(c.Request().URI().Path(), []byte("/.well-known/acme-challenge")) {
return c.Next()
}
// Skip Frontend and API routes
if bytes.HasPrefix(c.Request().URI().Path(), []byte("/runner")) {
return c.Next()
}
// Find deployment by domain
deployment := getDeploymentByDomain(strings.Split(c.Hostname(), ":")[0]) // Remove port
if deployment == nil {
return fiber.NewError(fiber.StatusNotFound, "Deployment not found")
}
if deployment.Status != "Running" {
return c.Redirect("/runner/deployment/" + deployment.Id + "/logs?logType=build")
}
// Rewrite request host
url := c.Request().URI()
// Always downgrade to http
url.SetScheme("http")
url.SetHost(fmt.Sprintf("127.0.0.1:%s", *deployment.Port))
err := proxy.Do(c, url.String())
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
resp := c.Response()
deployment.RequestsLogLock.Lock()
deployment.RequestsLog = append(
deployment.RequestsLog,
fmt.Sprintf("%s %s %d", c.Method(), c.Path(), resp.StatusCode()),
)
deployment.RequestsLogLock.Unlock()
//return c.Next()
return nil
})
if ssl {
// Certificate manager
m := &autocert.Manager{
Prompt: autocert.AcceptTOS,
// Replace with your domain
HostPolicy: func(_ context.Context, host string) error {
if host == domain {
return nil
}
if matches := regexp.MustCompile(`^[^.]+\.` + domain + `$`).MatchString(host); !matches {
return errors.New(
"acme/autocert: host name does not match any domain given in SAN",
)
}
return nil
},
// Folder to store the certificates
Cache: autocert.DirCache("./certs"),
}
// TLS Config
cfg := &tls.Config{
// Get Certificate from Let's Encrypt
GetCertificate: m.GetCertificate,
// By default NextProtos contains the "h2"
// This has to be removed since Fasthttp does not support HTTP/2
// Or it will cause a flood of PRI method logs
// http://webconcepts.info/concepts/http-method/PRI
NextProtos: []string{
"http/1.1", "acme-tls/1",
},
}
// Register acme challenge handler on http server
app.Get("/.well-known/acme-challenge/*", func(c *fiber.Ctx) error {
handler := fasthttpadaptor.NewFastHTTPHandler(m.HTTPHandler(nil))
handler(c.Context())
return nil
})
go func() {
ln, err := tls.Listen("tcp", fmt.Sprintf(":%s", sslPort), cfg)
if err != nil {
panic(err)
}
// Start server
log.Println("HTTPS Listening on port:", sslPort)
log.Fatal(app.Listener(ln))
}()
}
log.Println("HTTP Listening on port:", port)
log.Fatal(app.Listen(fmt.Sprintf(":%s", port)))
}