-
Notifications
You must be signed in to change notification settings - Fork 0
/
glue.go
97 lines (85 loc) · 2.52 KB
/
glue.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
package cmd
import (
"context"
"errors"
"fmt"
"github.com/mraron/njudge/internal/glue"
"github.com/mraron/njudge/internal/web"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"io/fs"
"log/slog"
"strings"
"time"
)
type GlueConfig struct {
Database web.DatabaseConfig `mapstructure:"db"`
DiscordWebhookURL string `mapstructure:"discord_webhook_url" yaml:"discord_webhook_url"`
}
var DefaultGlueConfig = GlueConfig{
Database: _dockerDatabaseConfig,
}
func NewGlueCmd(v *viper.Viper) *cobra.Command {
cfg := DefaultGlueConfig
cmd := &cobra.Command{
Use: "glue",
Short: "start glue service",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
v.SetConfigType("yaml")
v.SetConfigFile("glue.yaml")
v.AddConfigPath(".")
v.SetEnvPrefix("njudge")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
BindEnvs(GlueConfig{})
if err := v.ReadInConfig(); err != nil {
var res *fs.PathError
if !errors.As(err, &res) {
return err
}
}
cmd.Flags().VisitAll(func(flag *pflag.Flag) {
configName := flag.Name
if !flag.Changed && v.IsSet(configName) {
val := v.Get(configName)
_ = cmd.Flags().Set(flag.Name, fmt.Sprintf("%v", val))
}
})
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
if err := v.Unmarshal(&cfg); err != nil {
return err
}
conn, err := cfg.Database.ConnectAndPing(slog.Default())
if err != nil {
return err
}
logger := getHookedLogger(cfg.DiscordWebhookURL)
judges := glue.NewJudges(conn, logger)
go func() {
for {
judges.Update(context.Background())
time.Sleep(10 * time.Second)
}
}()
g, err := glue.New(
judges,
glue.WithDatabaseOption(conn),
glue.WithLogger(logger),
)
if err != nil {
return err
}
g.Start(cmd.Context())
return nil
},
}
cmd.Flags().StringVar(&cfg.Database.User, "db.user", DefaultGlueConfig.Database.User, "database user")
cmd.Flags().StringVar(&cfg.Database.Password, "db.password", DefaultGlueConfig.Database.Password, "database password")
cmd.Flags().StringVar(&cfg.Database.Host, "db.host", DefaultGlueConfig.Database.Host, "database host")
cmd.Flags().StringVar(&cfg.Database.Name, "db.name", DefaultGlueConfig.Database.Name, "database name")
cmd.Flags().IntVar(&cfg.Database.Port, "db.port", DefaultGlueConfig.Database.Port, "database port")
cmd.Flags().BoolVar(&cfg.Database.SSLMode, "db.ssl_mode", DefaultGlueConfig.Database.SSLMode, "database sslmode")
return cmd
}