forked from WelcomerTeam/Sandwich-Daemon
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
149 lines (119 loc) · 4.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
package main
import (
"flag"
"fmt"
"io"
"net/url"
"os"
"os/signal"
"path"
"strconv"
"syscall"
"time"
internal "github.com/WelcomerTeam/Sandwich-Daemon/internal"
"github.com/WelcomerTeam/Sandwich-Daemon/sandwichjson"
_ "github.com/joho/godotenv/autoload"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"gopkg.in/natefinch/lumberjack.v2"
)
const (
PermissionsDefault = 0o744
int64Base = 10
int64BitSize = 64
)
func main() {
prometheusAddress := flag.String("prometheusAddress", os.Getenv("PROMETHEUS_ADDRESS"), "Prometheus address")
configurationPath := flag.String("configurationPath", os.Getenv("CONFIGURATION_PATH"), "Path of configuration file (default: sandwich.yaml)")
gatewayURL := flag.String("gatewayURL", os.Getenv("GATEWAY_URL"), "Websocket for discord gateway")
baseURL := flag.String("baseURL", os.Getenv("BASE_URL"), "BaseURL to send HTTP requests to. If empty, will use https://discord.com")
httpHost := flag.String("httpHost", os.Getenv("HTTP_HOST"), "Host to use for internal dashboard.")
httpEnabled := flag.Bool("httpEnabled", MustParseBool(os.Getenv("HTTP_ENABLED")), "Enables the internal dashboard.")
loggingLevel := flag.String("level", os.Getenv("LOGGING_LEVEL"), "Logging level")
loggingFileLoggingEnabled := flag.Bool("fileLoggingEnabled", MustParseBool(os.Getenv("LOGGING_FILE_LOGGING_ENABLED")), "When enabled, will save logs to files")
loggingEncodeAsJSON := flag.Bool("encodeAsJSON", MustParseBool(os.Getenv("LOGGING_ENCODE_AS_JSON")), "When enabled, will save logs as JSON")
loggingCompress := flag.Bool("compress", MustParseBool(os.Getenv("LOGGING_COMPRESS")), "If true, will compress log files once reached max size")
loggingDirectory := flag.String("directory", os.Getenv("LOGGING_DIRECTORY"), "Directory to store logs in")
loggingFilename := flag.String("filename", os.Getenv("LOGGING_FILENAME"), "Filename to store logs as")
loggingMaxSize := flag.Int("maxSize", MustParseInt(os.Getenv("LOGGING_MAX_SIZE")), "Maximum size for log files before being split into separate files")
loggingMaxBackups := flag.Int("maxBackups", MustParseInt(os.Getenv("LOGGING_MAX_BACKUPS")), "Maximum number of log files before being deleted")
loggingMaxAge := flag.Int("maxAge", MustParseInt(os.Getenv("LOGGING_MAX_AGE")), "Maximum age in days for a log file")
flag.Parse()
// Setup Logger
level, err := zerolog.ParseLevel(*loggingLevel)
if err != nil {
panic(fmt.Errorf(`failed to parse loggingLevel. zerolog.ParseLevel(%s): %w`, *loggingLevel, err))
}
zerolog.SetGlobalLevel(level)
writer := zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: time.Stamp,
}
var writers []io.Writer
writers = append(writers, writer)
if *loggingFileLoggingEnabled {
if err := os.MkdirAll(*loggingDirectory, PermissionsDefault); err != nil {
log.Error().Err(err).Str("path", *loggingDirectory).Msg("Unable to create log directory")
} else {
lumber := &lumberjack.Logger{
Filename: path.Join(*loggingDirectory, *loggingFilename),
MaxBackups: *loggingMaxBackups,
MaxSize: *loggingMaxSize,
MaxAge: *loggingMaxAge,
Compress: *loggingCompress,
}
if *loggingEncodeAsJSON {
writers = append(writers, lumber)
} else {
writers = append(writers, zerolog.ConsoleWriter{
Out: lumber,
TimeFormat: time.Stamp,
NoColor: true,
})
}
}
}
mw := io.MultiWriter(writers...)
logger := zerolog.New(mw).With().Timestamp().Logger()
logger.Info().Msg("Logging configured")
// Send json parsing stuff
logger.Info().Bool("useSonic", sandwichjson.UseSonic).Msg("SandwichJson config")
options := internal.SandwichOptions{
ConfigurationLocation: *configurationPath,
PrometheusAddress: *prometheusAddress,
HTTPHost: *httpHost,
HTTPEnabled: *httpEnabled,
}
if confGatewayURL, err := url.Parse(*gatewayURL); err == nil {
options.GatewayURL = *confGatewayURL
} else {
panic(fmt.Sprintf(`url.Parse(%s): %v`, *baseURL, err))
}
if confBaseURL, err := url.Parse(*baseURL); err == nil {
options.BaseURL = *confBaseURL
} else {
panic(fmt.Sprintf(`url.Parse(%s): %v`, *baseURL, err))
}
// Sandwich initialization
sandwich, err := internal.NewSandwich(writer, options)
if err != nil {
panic(err)
}
sandwich.Open()
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-signalCh
err = sandwich.Close()
if err != nil {
logger.Warn().Err(err).Msg("Exception whilst closing sandwich")
}
logger.Info().Msg("Sandwich closed due to signal")
}
func MustParseBool(str string) bool {
boolean, _ := strconv.ParseBool(str)
return boolean
}
func MustParseInt(str string) int {
integer, _ := strconv.ParseInt(str, int64Base, int64BitSize)
return int(integer)
}