-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
289 lines (237 loc) · 7.9 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
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"gitlab.com/yakshaving.art/meeseeks-box/api"
"gitlab.com/yakshaving.art/meeseeks-box/config"
"gitlab.com/yakshaving.art/meeseeks-box/http"
"gitlab.com/yakshaving.art/meeseeks-box/meeseeks/executor"
"gitlab.com/yakshaving.art/meeseeks-box/meeseeks/metrics"
"gitlab.com/yakshaving.art/meeseeks-box/persistence"
"gitlab.com/yakshaving.art/meeseeks-box/remote/agent"
"gitlab.com/yakshaving.art/meeseeks-box/remote/server"
"gitlab.com/yakshaving.art/meeseeks-box/slack"
"gitlab.com/yakshaving.art/meeseeks-box/version"
"github.com/onrik/logrus/filename"
"github.com/sirupsen/logrus"
)
func main() {
args := parseArgs()
configureLogger(args)
shutdownFunc, reloadFunc, err := launch(args)
must("could not launch meeseeks-box: %s", err)
waitForSignals( // this locks for good, but receives a shutdown function
shutdownFunc,
reloadFunc)
logrus.Info("Everything has been shut down, bye bye!")
}
type args struct {
ConfigFile string
DebugMode bool
StealthMode bool
DebugSlack bool
Address string
APIPath string
MetricsPath string
SlackToken string
ExecutionMode string
AgentOf string
GRPCServerAddress string
GRPCServerEnabled bool
GRPCSecurityMode string
GRPCCertPath string
GRPCKeyPath string
}
func parseArgs() args {
configFile := flag.String("config", os.ExpandEnv("${HOME}/.meeseeks.yaml"), "meeseeks configuration file")
debugMode := flag.Bool("debug", false, "enabled debug mode")
debugSlack := flag.Bool("debug-slack", false, "enabled debug mode for slack")
showVersion := flag.Bool("version", false, "print the version and exit")
address := flag.String("http-address", ":9696", "http endpoint in which to listen")
apiPath := flag.String("api-path", "/message", "api path in to listen for api calls")
metricsPath := flag.String("metrics-path", "/metrics", "path to in which to expose prometheus metrics")
slackStealth := flag.Bool("stealth", false, "Enable slack stealth mode")
slackToken := flag.String("slack-token", os.Getenv("SLACK_TOKEN"), "slack token, by default loaded from the SLACK_TOKEN environment variable")
agentOf := flag.String("agent-of", "", "remote server to connect to, enables agent mode")
grpcServerAddress := flag.String("grpc-address", ":9697", "grpc server endpoint, used to connect remote agents")
grpcServerEnabled := flag.Bool("with-grpc-server", false, "enable grpc remote server to connect to")
grpcSecurityMode := flag.String("grpc-security-mode", "insecure", "grpc security mode, by default insecure, can be set to tls (for now)")
grpcCertPath := flag.String("grpc-cert-path", "", "Cert to use with the GRPC server")
grpcKeyPath := flag.String("grpc-key-path", "", "Key to use with the GRPC server")
flag.Parse()
if *showVersion {
logrus.Printf("Version: %s Commit: %s Date: %s", version.Version, version.Commit, version.Date)
os.Exit(0)
}
executionMode := "server"
if *agentOf != "" {
executionMode = "agent"
}
return args{
ConfigFile: *configFile,
DebugMode: *debugMode,
StealthMode: *slackStealth,
DebugSlack: *debugSlack,
SlackToken: *slackToken,
Address: *address,
APIPath: *apiPath,
MetricsPath: *metricsPath,
AgentOf: *agentOf,
GRPCServerAddress: *grpcServerAddress,
GRPCServerEnabled: *grpcServerEnabled,
GRPCSecurityMode: *grpcSecurityMode,
GRPCCertPath: *grpcCertPath,
GRPCKeyPath: *grpcKeyPath,
ExecutionMode: executionMode,
}
}
func launch(args args) (shutdownFunc func(), reloadFunc func(), err error) {
cnf, err := config.ReadFile(args.ConfigFile)
must("failed to load configuration file: %s", err)
must("could not load configuration: %s", config.LoadConfiguration(cnf))
reloadFunc = func() {
cnf, err := config.ReadFile(args.ConfigFile)
if err != nil {
logrus.Warnf("failed to read configuration file %s: %s", args.ConfigFile, err)
return
}
if err = config.LoadConfiguration(cnf); err != nil {
logrus.Warnf("failed to reload configuration %s: %s", args.ConfigFile, err)
} else {
logrus.Info("configuration successfully reloaded")
}
}
httpServer := listenHTTP(args)
switch args.ExecutionMode {
case "server":
must("Could not flush running jobs after: %s", persistence.Jobs().FailRunningJobs())
metrics.RegisterServerMetrics()
remoteServer, err := startRemoteServer(args)
must("could not start GRPC server: %s", err)
slackClient := connectToSlack(args)
apiService := startAPI(slackClient, args)
exc := executor.New(executor.Args{
ConcurrentTaskCount: 20,
WithBuiltinCommands: true,
ChatClient: slackClient,
})
exc.ListenTo(slackClient)
exc.ListenTo(apiService)
go exc.Run()
return func() {
exc.Shutdown()
httpServer.Shutdown()
remoteServer.Shutdown()
}, reloadFunc, nil
case "agent":
// metrics.RegisterAgentMetrics()
remoteClient := agent.New(agent.Configuration{
ServerURL: args.AgentOf,
Token: "null-token",
GRPCTimeout: 10 * time.Second,
Labels: map[string]string{},
SecurityMode: args.GRPCSecurityMode,
CertPath: args.GRPCCertPath,
})
must("could not connect to remote server: %s", remoteClient.Connect())
go remoteClient.Run()
logrus.Debugf("agent running connected to remote server: %s", args.AgentOf)
return func() {
remoteClient.Shutdown()
}, func() {
reloadFunc()
remoteClient.Reconnect()
}, nil
default:
return nil, nil, fmt.Errorf("Invalid execution mode %s, Valid execution modes are server (default), and agent",
args.ExecutionMode)
}
}
func configureLogger(args args) {
logrus.AddHook(filename.NewHook())
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
})
if args.DebugMode {
logrus.SetLevel(logrus.DebugLevel)
}
}
func connectToSlack(args args) *slack.Client {
logrus.Debug("Connecting to slack")
slackClient, err := slack.Connect(
slack.ConnectionOpts{
Debug: args.DebugSlack,
Token: args.SlackToken,
Stealth: args.StealthMode,
})
must("Could not connect to slack: %s", err)
logrus.Info("Connected to slack")
return slackClient
}
func listenHTTP(args args) *http.Server {
httpServer := http.New(args.Address)
metrics.RegisterPath(args.MetricsPath)
go func() {
logrus.Debug("Listening on http")
httpServer.ListenAndServe()
}()
logrus.Infof("Started HTTP server on %s", args.Address)
return httpServer
}
func startAPI(client *slack.Client, args args) *api.Service {
logrus.Debug("Starting api server")
return api.New(client, args.APIPath)
}
func startRemoteServer(args args) (*server.RemoteServer, error) {
s, err := server.New(server.Config{
CertPath: args.GRPCCertPath,
KeyPath: args.GRPCKeyPath,
SecurityMode: args.GRPCSecurityMode,
})
if err != nil {
return nil, fmt.Errorf("could not create GRPC Server: %s", err)
}
if args.GRPCServerEnabled {
logrus.Debugf("starting grpc remote server on %s", args.GRPCServerAddress)
go func() {
must("could not start grpc server", s.Listen(args.GRPCServerAddress))
}()
}
return s, nil
}
func waitForSignals(shutdownGracefully func(), reloadFunc func()) {
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGUSR1)
Loop:
for sig := range signalCh { // Listen for a signal forever
switch sig {
case syscall.SIGINT, syscall.SIGTERM:
logrus.Infof("Got signal %s, shutting down gracefully", sig)
break Loop
case syscall.SIGHUP:
logrus.Infof("Got signal %s, reloading the configuration", sig)
reloadFunc()
case syscall.SIGUSR1:
toggleDebugLogging()
}
}
shutdownGracefully()
}
func toggleDebugLogging() {
switch logrus.GetLevel() {
case logrus.DebugLevel:
logrus.SetLevel(logrus.InfoLevel)
default:
logrus.SetLevel(logrus.DebugLevel)
}
}
func must(message string, err error) {
if err != nil {
logrus.Fatalf(message, err)
os.Exit(1)
}
}