-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
397 lines (326 loc) · 12.7 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
package main
import (
"fmt"
"math"
"net"
"net/http"
"net/http/pprof"
"os"
"strings"
"sync"
"time"
"github.com/getsentry/sentry-go"
"github.com/gofrs/uuid/v3"
"github.com/gorilla/mux"
"github.com/orandin/sentrus"
"github.com/pkg/errors"
"github.com/robfig/cron/v3"
log "github.com/sirupsen/logrus"
"github.com/Luzifer/go_helpers/v2/str"
"github.com/Luzifer/rconfig/v2"
"github.com/Luzifer/twitch-bot/v3/internal/helpers"
"github.com/Luzifer/twitch-bot/v3/internal/service/access"
"github.com/Luzifer/twitch-bot/v3/internal/service/authcache"
"github.com/Luzifer/twitch-bot/v3/internal/service/timer"
"github.com/Luzifer/twitch-bot/v3/pkg/database"
"github.com/Luzifer/twitch-bot/v3/pkg/twitch"
)
const (
ircReconnectDelay = 100 * time.Millisecond
initialIRCRetryBackoff = 500 * time.Millisecond
ircRetryBackoffMultiplier = 1.5
maxIRCRetryBackoff = time.Minute
httpReadHeaderTimeout = 5 * time.Second
)
var (
cfg = struct {
BaseURL string `flag:"base-url" default:"" description:"External URL of the config-editor interface (used to generate auth-urls)"`
CommandTimeout time.Duration `flag:"command-timeout" default:"30s" description:"Timeout for command execution"`
Config string `flag:"config,c" default:"./config.yaml" description:"Location of configuration file"`
IRCRateLimit time.Duration `flag:"rate-limit" default:"1500ms" description:"How often to send a message (default: 20/30s=1500ms, if your bot is mod everywhere: 100/30s=300ms, different for known/verified bots)"`
LogLevel string `flag:"log-level" default:"info" description:"Log level (debug, info, warn, error, fatal)"`
PluginDir string `flag:"plugin-dir" default:"/usr/lib/twitch-bot" description:"Where to find and load plugins"`
SentryDSN string `flag:"sentry-dsn" default:"" description:"Sentry / GlitchTip DSN for error reporting"`
SentryEnvironment string `flag:"sentry-environment" default:"" description:"Environment to submit to Sentry to distinguish bot instances"`
StorageConnString string `flag:"storage-conn-string" default:"./storage.db" description:"Connection string for the database"`
StorageConnType string `flag:"storage-conn-type" default:"sqlite" description:"One of: mysql, postgres, sqlite"`
StorageEncryptionPass string `flag:"storage-encryption-pass" default:"" description:"Passphrase to encrypt secrets inside storage (defaults to twitch-client:twitch-client-secret)"`
TwitchClient string `flag:"twitch-client" default:"" description:"Client ID to act as"`
TwitchClientSecret string `flag:"twitch-client-secret" default:"" description:"Secret for the Client ID"`
ValidateConfig bool `flag:"validate-config,v" default:"false" description:"Loads the config, logs any errors and quits with status 0 on success"`
VersionAndExit bool `flag:"version" default:"false" description:"Prints current version and exits"`
WaitForSelfcheck time.Duration `flag:"wait-for-selfcheck" default:"60s" description:"Maximum time to wait for the self-check to respond when behind load-balancers"`
}{}
config *configFile
configLock = new(sync.RWMutex)
cronService *cron.Cron
ircHdl *ircHandler
router = mux.NewRouter()
runID = uuid.Must(uuid.NewV4()).String()
db database.Connector
accessService *access.Service
authService *authcache.Service
timerService *timer.Service
twitchClient *twitch.Client
version = "dev"
)
func initApp() error {
rconfig.AutoEnv(true)
if err := rconfig.ParseAndValidate(&cfg); err != nil {
return errors.Wrap(err, "parsing cli options")
}
if cfg.VersionAndExit {
fmt.Printf("twitch-bot %s\n", version) //nolint:forbidigo // Fine here
os.Exit(0) //revive:disable-line:deep-exit
}
l, err := log.ParseLevel(cfg.LogLevel)
if err != nil {
return errors.Wrap(err, "parsing log level")
}
log.SetLevel(l)
if cfg.SentryDSN != "" {
if err := sentry.Init(sentry.ClientOptions{
Dsn: cfg.SentryDSN,
Environment: cfg.SentryEnvironment,
Release: strings.Join([]string{"twitch-bot", version}, "@"),
}); err != nil {
return errors.Wrap(err, "initializing sentry sdk")
}
log.AddHook(sentrus.NewHook(
[]log.Level{log.ErrorLevel, log.FatalLevel, log.PanicLevel},
))
}
if cfg.StorageEncryptionPass == "" {
log.Warn("No storage encryption passphrase was set, falling back to client-id:client-secret")
cfg.StorageEncryptionPass = strings.Join([]string{
cfg.TwitchClient,
cfg.TwitchClientSecret,
}, ":")
}
return nil
}
//nolint:funlen,gocognit,gocyclo // Complexity is a little too high but makes no sense to split
func main() {
var err error
if err = initApp(); err != nil {
log.WithError(err).Fatal("initializing application")
}
if db, err = database.New(cfg.StorageConnType, cfg.StorageConnString, cfg.StorageEncryptionPass); err != nil {
log.WithError(err).Fatal("opening storage backend")
}
if accessService, err = access.New(db); err != nil {
log.WithError(err).Fatal("applying access migration")
}
authService = authcache.New(
authBackendInternalToken,
authBackendTwitchToken,
)
cronService = cron.New(cron.WithSeconds())
if timerService, err = timer.New(db, cronService); err != nil {
log.WithError(err).Fatal("applying timer migration")
}
// Allow config to subscribe to external rules
updCron := updateConfigCron()
if _, err = cronService.AddFunc(updCron, updateConfigFromRemote); err != nil {
log.WithError(err).Error("adding remote-update cron")
}
log.WithField("cron", updCron).Debug("Initialized remote update cron")
router.Use(corsMiddleware)
router.HandleFunc("/openapi.html", handleSwaggerHTML)
router.HandleFunc("/openapi.json", handleSwaggerRequest)
router.HandleFunc("/selfcheck", func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, runID, http.StatusOK)
})
if os.Getenv("ENABLE_PROFILING") == "true" {
router.HandleFunc("/debug/pprof/", pprof.Index)
router.Handle("/debug/pprof/allocs", pprof.Handler("allocs"))
router.Handle("/debug/pprof/block", pprof.Handler("block"))
router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
router.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine"))
router.Handle("/debug/pprof/heap", pprof.Handler("heap"))
router.Handle("/debug/pprof/mutex", pprof.Handler("mutex"))
router.HandleFunc("/debug/pprof/profile", pprof.Profile)
router.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
router.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
router.HandleFunc("/debug/pprof/trace", pprof.Trace)
}
router.MethodNotAllowedHandler = corsMiddleware(http.HandlerFunc(func(res http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
// Most likely JS client asking for CORS headers
res.WriteHeader(http.StatusNoContent)
return
}
res.WriteHeader(http.StatusMethodNotAllowed)
}))
if err = initCorePlugins(); err != nil {
log.WithError(err).Fatal("Unable to load core plugins")
}
if err = loadPlugins(cfg.PluginDir); err != nil {
log.WithError(err).Fatal("Unable to load plugins")
}
if len(rconfig.Args()) > 1 {
if err = cliTool.Call(rconfig.Args()[1:]); err != nil {
log.Fatalf("error in command: %s", err)
}
return
}
if err = db.ValidateEncryption(); err != nil {
log.WithError(err).Fatal("validation of database encryption failed, fix encryption passphrase or use 'twitch-bot reset-secrets' to wipe encrypted data")
}
if err = loadConfig(cfg.Config); err != nil {
if os.IsNotExist(errors.Cause(err)) {
if err = writeDefaultConfigFile(cfg.Config); err != nil {
log.WithError(err).Fatal("Initial config not found and not able to create example config")
}
log.WithField("filename", cfg.Config).Warn("No config was found, created example config: Please review that config!")
return
}
log.WithError(err).Fatal("Initial config load failed")
}
defer func() {
config.CloseRawMessageWriter() //nolint:errcheck,gosec,revive // That close is enforced by process exit
}()
if cfg.ValidateConfig {
// We were asked to only validate the config, this was successful
log.Info("Config validated successfully")
return
}
if err = startCheck(); err != nil {
log.WithError(err).Fatal("Missing required parameters")
}
if twitchClient, err = accessService.GetBotTwitchClient(access.ClientConfig{
TwitchClient: cfg.TwitchClient,
TwitchClientSecret: cfg.TwitchClientSecret,
TokenUpdateHook: func() {
// make frontend reload its state as of token change
frontendNotifyHooks.Ping(frontendNotifyTypeReload)
},
}); err != nil {
if !errors.Is(err, access.ErrChannelNotAuthorized) {
log.WithError(err).Fatal("initializing Twitch client")
}
twitchClient = twitch.New(cfg.TwitchClient, cfg.TwitchClientSecret, "", "")
}
twitchWatch := newTwitchWatcher()
// Query may run that often as the twitchClient has an internal
// cache but shouldn't run more often as EventSub subscriptions
// are retried on error each time
if _, err = cronService.AddFunc("@every 30s", twitchWatch.Check); err != nil {
log.WithError(err).Fatal("registering twitchWatch cron")
}
fsEvents := make(chan configChangeEvent, 1)
go watchConfigChanges(cfg.Config, fsEvents)
var (
ircDisconnected = make(chan struct{}, 1)
ircRetryBackoff = initialIRCRetryBackoff
autoMessageTicker = time.NewTicker(time.Second)
)
cronService.Start()
if config.HTTPListen != "" {
// If listen address is configured start HTTP server
listener, err := net.Listen("tcp", config.HTTPListen)
if err != nil {
log.WithError(err).Fatal("Unable to open http_listen port")
}
server := &http.Server{
ReadHeaderTimeout: httpReadHeaderTimeout, // gosec: G114 - Mitigate "slowloris" DoS attack vector
Handler: router,
}
go func() {
if err := server.Serve(listener); err != nil {
log.WithError(err).Fatal("running HTTP server")
}
}()
log.WithField("address", listener.Addr().String()).Info("HTTP server started")
}
for _, c := range config.Channels {
if err := twitchWatch.AddChannel(c); err != nil {
log.WithError(err).WithField("channel", c).Error("Unable to add channel to watcher")
}
}
ircDisconnected <- struct{}{}
for {
select {
case <-ircDisconnected:
if ircHdl != nil {
if err = ircHdl.Close(); err != nil {
log.WithError(err).Error("closing IRC handle")
}
}
if ircHdl, err = newIRCHandler(); err != nil {
log.WithError(err).Error("connecting to IRC")
go func() {
time.Sleep(ircRetryBackoff)
ircRetryBackoff = time.Duration(math.Min(float64(maxIRCRetryBackoff), float64(ircRetryBackoff)*ircRetryBackoffMultiplier))
ircDisconnected <- struct{}{}
}()
continue
}
ircRetryBackoff = initialIRCRetryBackoff // Successfully created, reset backoff
go func() {
log.Info("(re-)connecting IRC client")
if err := ircHdl.Run(); err != nil {
log.WithError(helpers.CleanNetworkAddressFromError(err)).Error("IRC run exited unexpectedly")
}
time.Sleep(ircReconnectDelay)
ircDisconnected <- struct{}{}
}()
case evt := <-fsEvents:
switch evt {
case configChangeEventUnkown:
continue
case configChangeEventNotExist:
log.Error("Config file is not available, not reloading config")
continue
case configChangeEventModified:
// Fine, reload
}
previousChannels := append([]string{}, config.Channels...)
if err := loadConfig(cfg.Config); err != nil {
log.WithError(err).Error("Unable to reload config")
continue
}
if ircHdl != nil {
ircHdl.ExecuteJoins(config.Channels)
}
for _, c := range config.Channels {
if err := twitchWatch.AddChannel(c); err != nil {
log.WithError(err).WithField("channel", c).Error("Unable to add channel to watcher")
}
}
for _, c := range previousChannels {
if !str.StringInSlice(c, config.Channels) {
log.WithField("channel", c).Info("Leaving removed channel...")
ircHdl.ExecutePart(c)
if err := twitchWatch.RemoveChannel(c); err != nil {
log.WithError(err).WithField("channel", c).Error("Unable to remove channel from watcher")
}
}
}
case <-autoMessageTicker.C:
configLock.RLock()
for _, am := range config.AutoMessages {
if !am.CanSend() {
continue
}
if err := am.Send(ircHdl.c); err != nil {
log.WithError(err).Error("Unable to send automated message")
}
}
configLock.RUnlock()
}
}
}
func startCheck() error {
var errs []string
if cfg.TwitchClient == "" {
errs = append(errs, "No Twitch-ClientId given")
}
if cfg.TwitchClientSecret == "" {
errs = append(errs, "No Twitch-ClientSecret given")
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, ", "))
}
return nil
}