-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathmain.go
348 lines (311 loc) · 11.6 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
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"net/http"
"os"
"path/filepath"
"sync"
"syscall"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/google/wire"
"github.com/newscred/webhook-broker/config"
"github.com/newscred/webhook-broker/controllers"
"github.com/newscred/webhook-broker/dispatcher"
"github.com/newscred/webhook-broker/prune"
"github.com/newscred/webhook-broker/storage"
"github.com/newscred/webhook-broker/storage/data"
"github.com/newscred/webhook-broker/utils"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
// ServerLifecycleListenerImpl is a blocking implementation around main method to wait on server actions
type ServerLifecycleListenerImpl struct {
shutdownListener chan bool
}
// StartingServer called when listening is being started
func (impl *ServerLifecycleListenerImpl) StartingServer() {}
// ServerStartFailed called when server start failed due to error
func (impl *ServerLifecycleListenerImpl) ServerStartFailed(err error) {}
// ServerShutdownCompleted called once server has been shutdown
func (impl *ServerLifecycleListenerImpl) ServerShutdownCompleted() {
go func() {
impl.shutdownListener <- true
}()
}
// HTTPServiceContainer wrapper for IoC too return
type HTTPServiceContainer struct {
Configuration *config.Config
Server *http.Server
DataAccessor storage.DataAccessor
Listener *ServerLifecycleListenerImpl
Dispatcher dispatcher.MessageDispatcher
}
var (
exit = func(code int) {
os.Exit(code)
}
consolePrintln = func(output string) {
fmt.Println(output)
}
// ErrMigrationSrcNotDir for error when migration source specified is not a directory
ErrMigrationSrcNotDir = errors.New("migration source not a dir")
parseArgs = func(programName string, args []string) (cliConfig *config.CLIConfig, output string, err error) {
flags := flag.NewFlagSet(programName, flag.ContinueOnError)
var buf bytes.Buffer
flags.SetOutput(&buf)
var conf config.CLIConfig
commandString := flags.String("command", string(config.BrokerCMD), "What operation this process is supposed to do")
flags.StringVar(&conf.ConfigPath, "config", "", "Config file location")
flags.StringVar(&conf.MigrationSource, "migrate", "", "Migration source folder")
flags.BoolVar(&conf.StopOnConfigChange, "stop-on-conf-change", false, "Restart internally on -config change if this flag is absent")
flags.BoolVar(&conf.DoNotWatchConfigChange, "do-not-watch-conf-change", false, "Do not watch config change")
err = flags.Parse(args)
if err != nil {
return nil, buf.String(), err
}
err = conf.SetCommandIfValid(*commandString)
if err != nil {
return nil, "command error", err
}
if len(conf.MigrationSource) > 0 {
fileInfo, err := os.Stat(conf.MigrationSource)
if err != nil {
return nil, "Could not determine migration source details", err
}
if !fileInfo.IsDir() {
return nil, "Migration source must be a dir", ErrMigrationSrcNotDir
}
if !filepath.IsAbs(conf.MigrationSource) {
conf.MigrationSource, _ = filepath.Abs(conf.MigrationSource)
}
conf.MigrationSource = "file://" + conf.MigrationSource
}
return &conf, buf.String(), nil
}
getApp = func(httpServiceContainer *HTTPServiceContainer) (*data.App, error) {
return httpServiceContainer.DataAccessor.GetAppRepository().GetApp()
}
startAppInit = func(httpServiceContainer *HTTPServiceContainer, seedData *config.SeedData) error {
return httpServiceContainer.DataAccessor.GetAppRepository().StartAppInit(seedData)
}
getTimeoutTimer = func() <-chan time.Time {
return time.After(time.Second * 10)
}
waitDuration = 1 * time.Second
initApp = func(httpServiceContainer *HTTPServiceContainer) {
app, err := getApp(httpServiceContainer)
var initFinished chan bool = make(chan bool)
timeout := getTimeoutTimer()
if err == nil && app.GetStatus() == data.NotInitialized || (app.GetStatus() == data.Initialized && app.GetSeedData().DataHash != httpServiceContainer.Configuration.GetSeedData().DataHash) {
go func() {
run := true
for run {
select {
case <-timeout:
initFinished <- true
run = false
default:
seedData := httpServiceContainer.Configuration.GetSeedData()
initErr := startAppInit(httpServiceContainer, &seedData)
switch initErr {
case nil:
createSeedData(httpServiceContainer.DataAccessor, httpServiceContainer.Configuration)
completeErr := httpServiceContainer.DataAccessor.GetAppRepository().CompleteAppInit()
log.Error().Err(completeErr).Msg("init error in setting complete flag")
run = false
case storage.ErrAppInitializing:
run = false
case storage.ErrOptimisticAppInit:
run = false
default:
log.Error().Err(initErr).Msg("unexpected init error")
time.Sleep(waitDuration)
}
}
}
initFinished <- true
}()
<-initFinished
}
}
createSeedData = func(dataAccessor storage.DataAccessor, seedDataConfig config.SeedDataConfig) {
for _, seedProducer := range seedDataConfig.GetSeedData().Producers {
producer, err := data.NewProducer(seedProducer.ID, seedProducer.Token)
if err == nil {
producer.Name = seedProducer.Name
_, err = dataAccessor.GetProducerRepository().Store(producer)
}
if err != nil {
log.Error().Err(err).Msg("Error creating producer: " + seedProducer.ID)
}
}
for _, seedChannel := range seedDataConfig.GetSeedData().Channels {
channel, err := data.NewChannel(seedChannel.ID, seedChannel.Token)
if err == nil {
channel.Name = seedChannel.Name
_, err = dataAccessor.GetChannelRepository().Store(channel)
}
if err != nil {
log.Error().Err(err).Msg("Error creating channel" + seedChannel.ID)
}
}
for _, seedConsumer := range seedDataConfig.GetSeedData().Consumers {
channel, err := dataAccessor.GetChannelRepository().Get(seedConsumer.Channel)
if err != nil {
log.Error().Err(err).Msg("no channel for the consumer as per spec")
continue
}
consumer, err := data.NewConsumer(channel, seedConsumer.ID, seedConsumer.Token, seedConsumer.CallbackURL, seedConsumer.Type)
if err == nil {
consumer.Name = seedConsumer.Name
consumer.ConsumingFrom = channel
consumer.CallbackURL = seedConsumer.CallbackURL.String()
_, err = dataAccessor.GetConsumerRepository().Store(consumer)
}
if err != nil {
log.Error().Err(err).Msg("Error creating consumer" + seedConsumer.ID)
}
}
}
)
func main() {
log.Print("Webhook Broker - " + string(GetAppVersion()))
inConfig, output, cliCfgErr := parseArgs(os.Args[0], os.Args[1:])
if cliCfgErr != nil {
consolePrintln(output)
if cliCfgErr != flag.ErrHelp {
log.Error().Err(cliCfgErr).Msg("CLI config error")
}
exit(1)
}
log.Print("Configuration File (optional): " + inConfig.ConfigPath)
if inConfig.Command == config.BrokerCMD {
// Start the webhook broker service
startWebhookBroker(inConfig)
} else {
pruneMessages(inConfig)
}
}
func pruneMessages(inConfig *config.CLIConfig) {
appConfig, err := config.GetConfigurationFromCLIConfig(inConfig) // appConfig
if err != nil {
log.Error().Err(err).Msg("could not use app config")
exit(10)
}
setupLogger(appConfig)
migrationConfig := GetMigrationConfig(inConfig)
dataAccessor, err := storage.GetNewDataAccessor(appConfig, migrationConfig, appConfig)
if err != nil {
log.Error().Err(err).Msg("could not connect to data storage")
exit(11)
}
err = prune.PruneMessages(dataAccessor, appConfig)
if err != nil {
log.Error().Err(err).Msg("could not prune messages")
exit(12)
}
}
func startWebhookBroker(inConfig *config.CLIConfig) {
hasConfigChange := true
var mutex sync.Mutex
var setHasConfigChange = func(newVal bool) {
mutex.Lock()
defer mutex.Unlock()
hasConfigChange = newVal
}
log.Print("On config change will stop? - ", inConfig.StopOnConfigChange)
pid := syscall.Getpid()
inConfig.NotifyOnConfigFileChange(func() {
log.Print("Config file changed")
if !inConfig.StopOnConfigChange {
log.Print("Restarting")
setHasConfigChange(true)
}
utils.NewProcessKiller().Kill(pid, syscall.SIGINT)
})
for hasConfigChange {
setHasConfigChange(false)
// Setup HTTP Server and listen (implicitly init DB and run migration if arg passed)
httpServiceContainer, err := GetHTTPServer(inConfig)
if err != nil {
log.Error().Err(err).Msg("could not start http service")
exit(3)
}
_, err = getApp(httpServiceContainer)
if err == nil {
initApp(httpServiceContainer)
} else {
log.Error().Err(err).Msg("could not retrieve app to initialize")
exit(4)
}
var buf bytes.Buffer
json.NewEncoder(&buf).Encode(httpServiceContainer.Configuration)
log.Print("Configuration in Use : " + buf.String())
// Setup Log Output
setupLogger(httpServiceContainer.Configuration)
<-httpServiceContainer.Listener.shutdownListener
httpServiceContainer.Dispatcher.Stop()
}
inConfig.StopWatcher()
}
func setupLogger(logConfig config.LogConfig) {
switch logConfig.GetLogLevel() {
case config.Debug:
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case config.Info:
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case config.Error:
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
case config.Fatal:
zerolog.SetGlobalLevel(zerolog.FatalLevel)
}
if logConfig.IsLoggerConfigAvailable() {
log.Logger = log.Output(&lumberjack.Logger{
Filename: logConfig.GetLogFilename(),
MaxSize: int(logConfig.GetMaxLogFileSize()), // megabytes
MaxBackups: int(logConfig.GetMaxLogBackups()),
MaxAge: int(logConfig.GetMaxAgeForALogFile()), //days
Compress: logConfig.IsCompressionEnabledOnLogBackups(), // disabled by default
})
}
}
// Providers & Injectors
// NewServerListener initializes new server listener
func NewServerListener() *ServerLifecycleListenerImpl {
return &ServerLifecycleListenerImpl{shutdownListener: make(chan bool)}
}
// GetMigrationConfig is provider for migration config
func GetMigrationConfig(cliConfig *config.CLIConfig) *storage.MigrationConfig {
return &storage.MigrationConfig{MigrationEnabled: cliConfig.IsMigrationEnabled(), MigrationSource: cliConfig.MigrationSource}
}
func newAppRepository(dataAccessor storage.DataAccessor) storage.AppRepository {
return dataAccessor.GetAppRepository()
}
func newProducerRepository(dataAccessor storage.DataAccessor) storage.ProducerRepository {
return dataAccessor.GetProducerRepository()
}
func newChannelRepository(dataAccessor storage.DataAccessor) storage.ChannelRepository {
return dataAccessor.GetChannelRepository()
}
func newConsumerRepository(dataAccessor storage.DataAccessor) storage.ConsumerRepository {
return dataAccessor.GetConsumerRepository()
}
func newMessageRepository(dataAccessor storage.DataAccessor) storage.MessageRepository {
return dataAccessor.GetMessageRepository()
}
func newDeliveryJobRepository(dataAccessor storage.DataAccessor) storage.DeliveryJobRepository {
return dataAccessor.GetDeliveryJobRepository()
}
func newLockRepository(dataAccessor storage.DataAccessor) storage.LockRepository {
return dataAccessor.GetLockRepository()
}
var (
httpServiceContainerInjectorSet = wire.NewSet(wire.Struct(new(HTTPServiceContainer), "Configuration", "Server", "DataAccessor", "Listener", "Dispatcher"))
configInjectorSet = wire.NewSet(httpServiceContainerInjectorSet, NewServerListener, GetMigrationConfig, wire.Bind(new(controllers.ServerLifecycleListener), new(*ServerLifecycleListenerImpl)), config.ConfigInjector)
relationalDBWithControllerSet = wire.NewSet(controllers.ControllerInjector, storage.GetNewDataAccessor, newLockRepository, newDeliveryJobRepository, newAppRepository, newChannelRepository, newProducerRepository, newConsumerRepository, newMessageRepository, dispatcher.MetricsInjector, dispatcher.DispatcherInjector)
)