-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
init.go
206 lines (193 loc) · 5.95 KB
/
init.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
package main
import (
"context"
"fmt"
"html/template"
"os"
"github.com/EduOJ/backend/app"
"github.com/EduOJ/backend/base"
"github.com/EduOJ/backend/base/event"
"github.com/EduOJ/backend/base/exit"
"github.com/EduOJ/backend/base/log"
"github.com/EduOJ/backend/base/utils"
"github.com/EduOJ/backend/base/validator"
"github.com/EduOJ/backend/database"
"github.com/EduOJ/backend/event/register"
runEvent "github.com/EduOJ/backend/event/run"
submissionEvent "github.com/EduOJ/backend/event/submission"
"github.com/go-mail/mail"
"github.com/go-redis/redis/v8"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/pkg/errors"
"github.com/spf13/viper"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func readConfig() {
log.Debug("Reading config.")
viper.SetConfigName("config") // name of config file (without extension)
viper.AddConfigPath("/etc/eduoj/") // path to look for the config file in
viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths
viper.AddConfigPath(".") // optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
}
func initLog() {
log.Debug("Initializing log.")
err := log.InitFromConfig()
if err != nil {
log.Fatal(errors.Wrap(err, "could not init log"))
os.Exit(-1)
}
log.Debug("Logging initialized.")
}
func initEvent() {
log.Debug("Initializing Event System.")
event.RegisterListener("run", runEvent.NotifyGetSubmissionPoll)
event.RegisterListener("submission", submissionEvent.UpdateGrade)
event.RegisterListener("register", register.SendVerificationEmail)
}
func startEcho() {
log.Debug("Starting echo server.")
port := viper.GetInt("server.port")
base.Echo = echo.New()
base.Echo.Logger = &log.EchoLogger{}
base.Echo.HideBanner = true
base.Echo.HidePort = true
base.Echo.Use(middleware.Recover())
base.Echo.Server.Addr = fmt.Sprintf(":%d", port)
base.Echo.Validator = validator.NewEchoValidator()
app.Register(base.Echo)
exit.QuitWG.Add(1)
go func() {
err := base.Echo.StartServer(base.Echo.Server)
if err != nil {
log.Fatal(errors.Wrap(err, "server closed"))
}
}()
log.Fatal("Server started at ", base.Echo.Server.Addr)
// When server closes, closes web server.
go func() {
<-exit.BaseContext.Done()
err := base.Echo.Shutdown(context.Background())
if err != nil {
if err.Error() == "context canceled" {
log.Fatal("Force quitting.")
} else {
log.Fatal(err)
}
}
exit.QuitWG.Done()
}()
}
func initRedis() {
log.Debug("Starting redis client.")
base.Redis = redis.NewClient(&redis.Options{
Addr: fmt.Sprint(viper.Get("redis.host"), ":", viper.GetInt("redis.port")),
Username: viper.GetString("redis.username"),
Password: viper.GetString("redis.password"),
})
// test connection.
_, err := base.Redis.Ping(context.Background()).Result()
if err != nil {
log.Fatal(errors.Wrap(err, "could not init redis"))
os.Exit(-1)
}
log.Debug("Redis client started.")
}
func initGorm(toMigrate ...bool) {
log.Debug("Starting database client.")
var err error
switch viper.GetString("database.dialect") {
case "mysql":
base.DB, err = gorm.Open(mysql.Open(viper.GetString("database.uri")), &gorm.Config{
Logger: log.GormLogger{},
})
case "postgres":
base.DB, err = gorm.Open(postgres.Open(viper.GetString("database.uri")), &gorm.Config{
Logger: log.GormLogger{},
})
case "sqlite":
base.DB, err = gorm.Open(sqlite.Open(viper.GetString("database.uri")), &gorm.Config{
Logger: log.GormLogger{},
DisableForeignKeyConstraintWhenMigrating: true,
})
default:
log.Fatal("unsupported database dialect")
os.Exit(-1)
}
if err != nil {
log.Fatal(errors.Wrap(err, "could not init database"))
os.Exit(-1)
}
if len(toMigrate) == 0 || toMigrate[0] {
database.Migrate()
}
log.Debug("Database client started.")
// Cause we need to wait until all logs are wrote to the db
// So we dont close db connection here.
}
func initMail() {
var err error
d := mail.NewDialer(viper.GetString("email.host"), viper.GetInt("email.port"), viper.GetString("email.username"), viper.GetString("email.password"))
if viper.GetBool("email.tls") {
d.StartTLSPolicy = mail.MandatoryStartTLS
}
base.Mail = *d
base.Template, err = template.ParseFiles("template/email_verification.html")
if err != nil {
log.Fatal(err)
}
}
func initStorage() {
log.Debug("Starting storage client.")
var err error
base.Storage, err = minio.New(viper.GetString("storage.endpoint"), &minio.Options{
Region: viper.GetString("storage.region"),
Creds: credentials.NewStaticV4(viper.GetString("storage.access_key_id"), viper.GetString("storage.access_key_secret"), ""),
Secure: viper.GetBool("storage.false"),
})
if err != nil {
log.Fatal(errors.Wrap(err, "could not connect to minio server."))
panic(err)
}
_, err = base.Storage.ListBuckets(context.Background())
if err != nil {
log.Fatal(errors.Wrap(err, "could not connect to minio server."))
panic(err)
}
if err := utils.CreateBucket("images"); err != nil {
panic(err)
}
if err := utils.CreateBucket("scripts"); err != nil {
panic(err)
}
if err := utils.CreateBucket("problems"); err != nil {
panic(err)
}
if err := utils.CreateBucket("submissions"); err != nil {
panic(err)
}
log.Debug("Storage client initialized.")
}
func initWebAuthn() {
var err error
base.WebAuthn, err = webauthn.New(&webauthn.Config{
RPDisplayName: viper.GetString("webauthn.display_name"),
RPID: viper.GetString("webauthn.domain"),
RPOrigin: viper.GetString("webauthn.origin"),
RPIcon: viper.GetString("webauthn.icon"),
})
if err != nil {
log.Fatal(err)
os.Exit(-1)
}
}