serverctl/services/entry/main.go

332 lines
8.7 KiB
Go
Raw Normal View History

2022-02-11 22:06:52 +01:00
package main
2022-02-13 18:09:26 +01:00
import (
"context"
"fmt"
2022-02-13 18:09:26 +01:00
"github.com/dgraph-io/ristretto"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/eko/gocache/cache"
2022-02-14 01:42:18 +01:00
"github.com/eko/gocache/metrics"
2022-02-13 18:09:26 +01:00
"github.com/eko/gocache/store"
"github.com/gin-gonic/gin"
"github.com/go-co-op/gocron"
"github.com/google/uuid"
"github.com/jackc/pgx/v4/pgxpool"
2022-02-14 01:42:18 +01:00
"github.com/prometheus/client_golang/prometheus/promhttp"
2022-02-13 18:09:26 +01:00
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"io/ioutil"
"log"
2022-02-13 18:09:26 +01:00
"net/http"
"os"
2022-02-14 01:25:36 +01:00
"serverctl/pkg/application/projects"
"serverctl/pkg/application/users"
2022-02-13 21:45:27 +01:00
"serverctl/pkg/db"
"serverctl/pkg/db/postgres"
2022-02-13 18:09:26 +01:00
"time"
)
import _ "net/http/pprof"
2022-02-13 18:09:26 +01:00
func setupLogger() *zap.Logger {
highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapcore.ErrorLevel
})
lowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl < zapcore.ErrorLevel
})
fileDebugging := zapcore.AddSync(ioutil.Discard)
fileErrors := zapcore.AddSync(ioutil.Discard)
consoleDebugging := zapcore.Lock(os.Stdout)
consoleErrors := zapcore.Lock(os.Stderr)
fileEncoder := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
2022-02-14 20:03:53 +01:00
_ = zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
2022-02-13 18:09:26 +01:00
core := zapcore.NewTee(
zapcore.NewCore(fileEncoder, fileErrors, highPriority),
2022-02-14 20:03:53 +01:00
zapcore.NewCore(fileEncoder, consoleErrors, highPriority),
2022-02-13 18:09:26 +01:00
zapcore.NewCore(fileEncoder, fileDebugging, lowPriority),
2022-02-14 20:03:53 +01:00
zapcore.NewCore(fileEncoder, consoleDebugging, lowPriority),
2022-02-13 18:09:26 +01:00
)
logger := zap.New(core)
defer logger.Sync()
return logger
}
2022-02-13 21:45:27 +01:00
func BasicAuthMiddleware(l *zap.Logger, us *users.Service) gin.HandlerFunc {
return func(c *gin.Context) {
username, password, hasAuth := c.Request.BasicAuth()
if !hasAuth {
l.Info("user could not be authenticated",
zap.String("username", username))
c.Header("WWW-Authenticate", "Basic realm=serverctl")
c.Abort()
c.JSON(http.StatusUnauthorized, gin.H{"message": "credentials were invalid (authorization header missing)"})
return
}
user, err := us.Authenticate(c.Request.Context(), username, password)
if err != nil {
l.Info("user could not be authenticated",
zap.String("username", username))
c.Abort()
c.Header("WWW-Authenticate", "Basic realm=serverctl")
c.JSON(http.StatusUnauthorized, gin.H{"message": "credentials were invalid (credentials didn't match)"})
return
}
l.Debug("user has been authenticated",
zap.Int("userId", user.Id),
zap.String("email", user.Email))
c.Set("userId", user.Id)
c.Next()
}
}
2022-02-14 01:42:18 +01:00
func setupApi(l *zap.Logger, cc *cache.MetricCache, us *users.Service, ps *projects.Service) {
2022-02-13 18:09:26 +01:00
l.Info("Setting up serverctl setupApi (using gin)")
r := gin.Default()
2022-02-14 01:42:18 +01:00
promHandler := func() gin.HandlerFunc {
h := promhttp.Handler()
return func(c *gin.Context) {
h.ServeHTTP(c.Writer, c.Request)
}
}
r.GET("/metrics", promHandler())
2022-02-13 21:45:27 +01:00
r.POST("/auth/register", func(c *gin.Context) {
type RegisterUser struct {
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
}
var registerUser RegisterUser
if err := c.BindJSON(&registerUser); err != nil {
return
}
createUser, err := us.Create(registerUser.Email, registerUser.Password)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "you have provided invalid input"})
return
}
c.JSON(http.StatusCreated, gin.H{"message": "user has been registered", "userId": createUser})
})
2022-02-14 01:25:36 +01:00
projectsApi := r.Group("/projects", BasicAuthMiddleware(l, us))
projectsApi.POST("/", func(c *gin.Context) {
type CreateProjectRequest struct {
Name string `json:"name" binding:"required"`
}
var createProjectRequest CreateProjectRequest
if err := c.BindJSON(&createProjectRequest); err != nil {
return
}
userId, _ := c.Get("userId")
createProjectId, err := ps.CreateProject(c.Request.Context(), userId.(int), createProjectRequest.Name)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "you have provided invalid input"})
return
}
c.JSON(http.StatusCreated, gin.H{"message": "project has been created", "projectId": createProjectId})
})
projectsApi.GET("/", func(c *gin.Context) {
userId, _ := c.Get("userId")
projectsArr, err := ps.Get(c.Request.Context(), userId.(int))
if err != nil {
l.Warn(err.Error())
return
}
2022-02-14 22:19:44 +01:00
type GetProjectMembers struct {
MemberId int `json:"memberId" binding:"required"`
MemberRole string `json:"memberRole" binding:"required"`
}
2022-02-14 01:25:36 +01:00
type GetProject struct {
2022-02-14 22:19:44 +01:00
Id int `json:"id" binding:"required"`
Name string `json:"name" binding:"required"`
Members []*GetProjectMembers `json:"members" binding:"required"`
}
membersAsGetProjectMembers := func(projectMembers []projects.ProjectMember) []*GetProjectMembers {
gpm := make([]*GetProjectMembers, len(projectMembers))
for i, pm := range projectMembers {
gpm[i] = &GetProjectMembers{
MemberId: pm.MemberId,
MemberRole: pm.Role,
}
}
return gpm
2022-02-14 01:25:36 +01:00
}
getProject := make([]GetProject, 0)
for _, p := range projectsArr {
getProject = append(getProject, GetProject{
2022-02-14 22:19:44 +01:00
Id: p.Id,
Name: p.Name,
Members: membersAsGetProjectMembers(p.Members),
2022-02-14 01:25:36 +01:00
})
}
c.JSON(http.StatusOK, getProject)
})
2022-02-13 21:45:27 +01:00
containers := r.Group("/containers", BasicAuthMiddleware(l, us))
containers.GET("/", func(c *gin.Context) {
2022-02-13 18:09:26 +01:00
type container struct {
Name string `json:"name"`
}
var msg struct {
Containers []container `json:"containers"`
}
get, err := cc.Get("docker-containers")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "could not get containers from container runtime"})
return
}
msg.Containers = []container{}
for _, cont := range get.([]types.Container) {
msg.Containers = append(msg.Containers, container{
Name: cont.Names[0],
})
}
c.JSON(http.StatusOK, msg)
})
r.Run(":8080")
}
func setupDocker(l *zap.Logger) *client.Client {
l.Info("Setting up Docker")
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
panic(err)
}
return cli
}
2022-02-14 01:42:18 +01:00
func setupCache(l *zap.Logger) *cache.MetricCache {
2022-02-13 18:09:26 +01:00
l.Info("Setting up cache")
ristrettoCache, err := ristretto.NewCache(&ristretto.Config{
NumCounters: 1000,
2022-02-14 01:25:36 +01:00
MaxCost: 100_000_000,
2022-02-13 18:09:26 +01:00
BufferItems: 64,
})
2022-02-14 01:42:18 +01:00
promMetrics := metrics.NewPrometheus("serverctl")
2022-02-13 18:09:26 +01:00
if err != nil {
panic(err)
}
ristrettoStore := store.NewRistretto(ristrettoCache, nil)
2022-02-14 01:42:18 +01:00
2022-02-13 18:09:26 +01:00
cacheManager := cache.New(ristrettoStore)
2022-02-14 01:42:18 +01:00
metricsCache := cache.NewMetric(promMetrics, cacheManager)
2022-02-13 18:09:26 +01:00
2022-02-14 01:42:18 +01:00
return metricsCache
2022-02-13 18:09:26 +01:00
}
2022-02-14 01:42:18 +01:00
func setupCron(l *zap.Logger, cm *cache.MetricCache, cc *client.Client) {
2022-02-13 18:09:26 +01:00
l.Info("Setting up job scheduler (cron)")
s := gocron.NewScheduler(time.UTC)
s.Every(10).Second().Do(func() {
l.Debug("getting container list")
list, err := cc.ContainerList(context.Background(), types.ContainerListOptions{})
if err != nil {
l.Warn(err.Error())
return
}
err = cm.Set("docker-containers", list, &store.Options{
Cost: 2,
})
if err != nil {
l.Warn(err.Error())
return
}
})
s.StartAsync()
}
2022-02-11 22:06:52 +01:00
func main() {
2022-02-13 18:09:26 +01:00
logger := setupLogger()
logger.Info("Starting serverctl")
cacheM := setupCache(logger)
containerClient := setupDocker(logger)
setupCron(logger, cacheM, containerClient)
2022-02-13 21:45:27 +01:00
database := db.NewClient(logger)
usersRepository := postgres.NewUsersRepository(database)
usersService := users.NewService(logger, usersRepository, cacheM)
2022-02-14 01:25:36 +01:00
projectsRepository := postgres.NewProjectsRepository(database)
projectsService := projects.NewService(logger, projectsRepository, cacheM)
2022-02-13 21:45:27 +01:00
setupProfiler()
addSeedData(database, usersRepository, projectsRepository)
2022-02-14 01:25:36 +01:00
setupApi(logger, cacheM, usersService, projectsService)
2022-02-11 22:06:52 +01:00
}
func setupProfiler() {
go func() {
log.Println(http.ListenAndServe(":6060", nil))
}()
}
func addSeedData(database *db.Client, ur users.Repository, pr projects.Repository) {
conn := database.GetConn(context.Background())
defer conn.Release()
var numRows int
err := conn.QueryRow(context.Background(), "select count(id) from sctl_user").Scan(&numRows)
if err != nil {
panic(err)
}
if numRows == 0 {
addTestData(conn, ur, pr)
}
}
func addTestData(conn *pgxpool.Conn, ur users.Repository, pr projects.Repository) {
ctx := context.Background()
for jobs := 0; jobs < 100; jobs++ {
go func() {
for i := 0; i < 1_000; i++ {
var (
user *users.CreateUser
err error
userId int
)
user, err = users.NewCreateUser(fmt.Sprintf("%s@test.com", uuid.New().String()), "password", users.NewPlainTextPasswordHasher())
if err != nil {
panic(err)
}
userId, err = ur.Create(ctx, user)
if err != nil {
panic(err)
}
_, err = pr.Create(ctx, projects.NewCreateProject(uuid.New().String()[:20], userId))
if err != nil {
panic(err)
}
}
}()
}
}