-
Notifications
You must be signed in to change notification settings - Fork 927
/
common.go
260 lines (206 loc) · 5.16 KB
/
common.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
package common
//go:generate sqlboiler --no-hooks psql
import (
"database/sql"
"fmt"
stdlog "log"
"math/rand"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/jonas747/discordgo"
"github.com/mediocregopher/radix/v3"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/sirupsen/logrus"
"github.com/volatiletech/sqlboiler/boil"
)
var (
VERSION = "unknown"
GORM *gorm.DB
PQ *sql.DB
RedisPool *radix.Pool
BotSession *discordgo.Session
BotUser *discordgo.User
RedisPoolSize = 0
Testing = os.Getenv("YAGPDB_TESTING") != ""
CurrentRunCounter int64
NodeID string
// if your compile failed at this line, you're likely not compiling for 64bit, which is unsupported.
_ interface{} = ensure64bit
logger = GetFixedPrefixLogger("common")
)
// CoreInit initializes the essential parts
func CoreInit() error {
rand.Seed(time.Now().UnixNano())
stdlog.SetOutput(&STDLogProxy{})
stdlog.SetFlags(0)
if Testing {
logrus.SetLevel(logrus.DebugLevel)
}
err := connectRedis()
if err != nil {
return err
}
err = LoadConfig()
if err != nil {
return err
}
return nil
}
// Init initializes the rest of the bot
func Init() error {
err := setupGlobalDGoSession()
if err != nil {
return err
}
db := "yagpdb"
if ConfPQDB.GetString() != "" {
db = ConfPQDB.GetString()
}
err = connectDB(ConfPQHost.GetString(), ConfPQUsername.GetString(), ConfPQPassword.GetString(), db, confMaxSQLConns.GetInt())
if err != nil {
panic(err)
}
logger.Info("Retrieving bot info....")
BotUser, err = BotSession.UserMe()
if err != nil {
panic(err)
}
BotSession.State.User = &discordgo.SelfUser{
User: BotUser,
}
err = RedisPool.Do(radix.Cmd(&CurrentRunCounter, "INCR", "yagpdb_run_counter"))
if err != nil {
panic(err)
}
logger.Info("Initializing core schema")
InitSchemas("core_configs", CoreServerConfDBSchema)
return err
}
func GetBotToken() string {
token := ConfBotToken.GetString()
if !strings.HasPrefix(token, "Bot ") {
token = "Bot " + token
}
return token
}
func setupGlobalDGoSession() (err error) {
BotSession, err = discordgo.New(GetBotToken())
if err != nil {
return err
}
maxCCReqs := ConfMaxCCR.GetInt()
if maxCCReqs < 1 {
maxCCReqs = 25
}
logger.Info("max ccr set to: ", maxCCReqs)
BotSession.MaxRestRetries = 10
BotSession.Ratelimiter.MaxConcurrentRequests = maxCCReqs
innerTransport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 10 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
MaxIdleConnsPerHost: maxCCReqs,
TLSHandshakeTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if ConfDisableKeepalives.GetBool() {
innerTransport.DisableKeepAlives = true
logger.Info("Keep alive connections to REST api for discord is disabled, may cause overhead")
}
BotSession.Client.Transport = &LoggingTransport{Inner: innerTransport}
return nil
}
func InitTest() {
testDB := os.Getenv("YAGPDB_TEST_DB")
if testDB == "" {
return
}
err := connectDB("localhost", "postgres", "123", testDB, 3)
if err != nil {
panic(err)
}
}
var (
metricsRedisReconnects = promauto.NewCounter(prometheus.CounterOpts{
Name: "yagpdb_redis_reconnects_total",
Help: "Number of reconnects to the redis server",
})
metricsRedisRetries = promauto.NewCounter(prometheus.CounterOpts{
Name: "yagpdb_redis_retries_total",
Help: "Number of retries on redis commands",
})
)
func connectRedis() (err error) {
maxConns := RedisPoolSize
if maxConns == 0 {
maxConns, _ = strconv.Atoi(os.Getenv("YAGPDB_REDIS_POOL_SIZE"))
if maxConns == 0 {
maxConns = 10
}
}
logger.Infof("Set redis pool size to %d", maxConns)
// we kinda bypass the config system because the config system also relies on redis
// this way the only required env var is the redis address, and per-host specific things
addr := os.Getenv("YAGPDB_REDIS")
if addr == "" {
addr = "localhost:6379"
}
RedisPool, err = radix.NewPool("tcp", addr, maxConns, radix.PoolOnEmptyWait(), radix.PoolOnFullClose(), radix.PoolPipelineWindow(0, 0))
return
}
func connectDB(host, user, pass, dbName string, maxConns int) error {
if host == "" {
host = "localhost"
}
passwordPart := ""
if pass != "" {
passwordPart = " password='" + pass + "'"
}
db, err := gorm.Open("postgres", fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable%s", host, user, dbName, passwordPart))
GORM = db
PQ = db.DB()
boil.SetDB(PQ)
if err == nil {
PQ.SetMaxOpenConns(maxConns)
PQ.SetMaxIdleConns(maxConns)
logger.Infof("Set max PG connections to %d", maxConns)
}
GORM.SetLogger(&GORMLogger{})
return err
}
var (
shutdownFunc func()
shutdownCalled bool
shutdownMU sync.Mutex
)
func Shutdown() {
shutdownMU.Lock()
f := shutdownFunc
if f == nil || shutdownCalled {
shutdownMU.Unlock()
return
}
shutdownCalled = true
shutdownMU.Unlock()
if f != nil {
f()
}
}
func SetShutdownFunc(f func()) {
shutdownMU.Lock()
shutdownFunc = f
shutdownMU.Unlock()
}