-
Notifications
You must be signed in to change notification settings - Fork 0
/
root.go
239 lines (198 loc) · 6.03 KB
/
root.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
package main
import (
"fmt"
"io"
"os"
"os/signal"
"path"
"sync"
"syscall"
"time"
"github.com/bubblesupreme/banner_rotation/internal/app"
"github.com/bubblesupreme/banner_rotation/internal/multiarmed_bandit/thompson"
rabbitmqproducer "github.com/bubblesupreme/banner_rotation/internal/producer/rabbitmq_producer"
"github.com/bubblesupreme/banner_rotation/internal/server"
"github.com/NeowayLabs/wabbit/amqp"
sqlrepository "github.com/bubblesupreme/banner_rotation/internal/repository/sql"
_ "github.com/bubblesupreme/banner_rotation/migrations"
"github.com/fsnotify/fsnotify"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
homedir "github.com/mitchellh/go-homedir"
"github.com/pressly/goose"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/net/context"
)
const (
driver = "postgres"
layoutTime = "01-02-2006-15-04-05"
minEvents = 50
)
var cfgFile string
var rootCmd = &cobra.Command{
Use: "banner_rotation",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: run,
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.banner_rotation.yaml)")
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
log.Fatal(err)
}
// Search config in home directory with name "calendar.json".
viper.AddConfigPath(home)
viper.SetConfigName("banners.json")
}
viper.SetConfigType("json")
viper.AutomaticEnv()
viper.BindEnv("dblogin", "POSTGRES_USER")
viper.BindEnv("dbname", "POSTGRES_DB")
viper.BindEnv("dbpassword", "POSTGRES_PASSWORD")
viper.BindEnv("migrations", "MIGRATIONS_DIRECTORY")
readConfig()
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config was changed: ", e.Name)
readConfig()
})
}
func readConfig() {
if err := viper.ReadInConfig(); err == nil {
log.Info("using config file: " + viper.ConfigFileUsed())
} else {
log.Fatal("failed to read config file: " + err.Error())
}
}
func run(_ *cobra.Command, args []string) {
config, err := NewConfig()
if err != nil {
log.Fatal("failed to read config: ", err.Error())
}
logF, err := configureLogger(config)
if err != nil {
log.Fatal("failed to configure logger: ", err.Error())
}
defer func() {
if err := logF.Close(); err != nil {
log.Panic("failed to close log file: ", err.Error())
}
}()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
db, err := sqlx.Connect(driver, fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s sslmode=disable",
config.DataBase.Host, config.DataBase.Port, config.DataBase.Login, config.DataBase.DBName, config.DataBase.Password))
if err != nil {
log.WithFields(log.Fields{
"host": config.DataBase.Host,
"port": config.DataBase.Port,
"login": config.DataBase.Login,
"dbname": config.DataBase.DBName,
"password": config.DataBase.Password,
}).Fatal("failed to connect to database :", err.Error())
}
defer func() {
if err := db.Close(); err != nil {
log.Fatal("failed to close database: ", err.Error())
}
}()
if err := goose.Up(db.DB, config.DataBase.MigrationsDir); err != nil {
log.Error("failed to migrate: ", err.Error())
return
}
bandit, err := thompson.NewThompsonBandit(minEvents)
if err != nil {
log.Error("failed to initialize multi-armed bandit: ", err.Error())
return
}
repo := sqlrepository.NewSQLRepository(db.DB, bandit)
rabbitConnection, err := amqp.Dial(config.Rabbit.URL)
if err != nil {
log.Error("failed to initialize rabbit connection: ", err.Error())
return
}
producer, err := rabbitmqproducer.NewProducer(
rabbitConnection,
config.Rabbit.ExchangeName,
config.Rabbit.ClickRoutingKey,
config.Rabbit.ShowRoutingKey)
if err != nil {
log.Error("failed to initialize RabbitMQ producer: ", err.Error())
return
}
a := app.NewBannersApp(repo, producer)
s := server.NewServer(a, config.Server.Port)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGHUP)
select {
case <-ctx.Done():
return
case <-signals:
}
signal.Stop(signals)
cancel()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
if err := s.Stop(ctx); err != nil {
log.Error("failed to stop http server: " + err.Error())
}
}()
if err := s.Start(ctx); err != nil {
log.Error("failed to start http server: " + err.Error())
cancel()
return
}
wg.Wait()
}
func configureLogger(c Config) (*os.File, error) {
l, err := log.ParseLevel(c.Logger.Level)
if err != nil {
log.WithField("level string", c.Logger.Level).Errorf("failed to parse level: " + err.Error())
return nil, err
}
log.SetLevel(l)
fileName := fmt.Sprint("banners", time.Now().Format(layoutTime), ".log")
if err := os.MkdirAll(c.Logger.Path, os.ModePerm); err != nil {
log.WithFields(log.Fields{
"path": c.Logger.Path,
}).Errorf("failed to create log directory")
return nil, err
}
f, err := os.OpenFile(path.Join(c.Logger.Path, fileName), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o755)
if err != nil {
log.WithFields(log.Fields{
"path": c.Logger.Path,
"file name": fileName,
}).Errorf("failed to create log file: " + err.Error())
return nil, err
}
log.SetOutput(io.MultiWriter(f, os.Stdout))
return f, nil
}