forked from islax/microapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
289 lines (251 loc) · 10.6 KB
/
app.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 microapp
import (
"context"
"database/sql"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
migrate "github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/mysql"
"github.com/golang-migrate/migrate/v4/source/file"
"github.com/gorilla/mux"
"github.com/islax/microapp/config"
microappCtx "github.com/islax/microapp/context"
"github.com/islax/microapp/event"
"github.com/islax/microapp/log"
"github.com/islax/microapp/repository"
"github.com/islax/microapp/retry"
"github.com/islax/microapp/security"
"github.com/jinzhu/gorm"
"github.com/rs/zerolog"
uuid "github.com/satori/go.uuid"
)
// RouteSpecifier should be implemented by the class that sets routes for the API endpoints
type RouteSpecifier interface {
RegisterRoutes(router *mux.Router)
}
// App structure for tenant microservice
type App struct {
Name string
Config *config.Config
DB *gorm.DB
Router *mux.Router
server *http.Server
log zerolog.Logger
eventDispatcher event.Dispatcher
}
// NewWithEnvValues creates a new application with environment variable values for initializing database, event dispatcher and logger.
func NewWithEnvValues(appName string, appConfigDefaults map[string]interface{}) *App {
appConfig := config.NewConfig(appConfigDefaults)
log.InitializeGlobalSettings()
consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
consoleOnlyLogger := log.New(appName, appConfig.GetString("LOG_LEVEL"), consoleWriter)
// consoleOnlyLogger := zerolog.New(consoleWriter).With().Timestamp().Str("service", appName).Logger().Level()
multiWriters := io.MultiWriter(consoleWriter)
var err error
var appEventDispatcher event.Dispatcher
if appConfig.GetStringWithDefault("ENABLE_EVENT_DISPATCHER", "0") == "1" || appConfig.GetStringWithDefault("LOG_TO_EVENTQ", "0") == "1" {
if appEventDispatcher, err = event.NewRabbitMQEventDispatcher(consoleOnlyLogger); err != nil {
consoleOnlyLogger.Fatal().Err(err).Msg("Failed to initialize event dispatcher to queue, exiting the application!")
}
if appConfig.GetStringWithDefault("LOG_TO_EVENTQ", "0") == "1" {
multiWriters = io.MultiWriter(consoleWriter, event.NewEventQWriter(appEventDispatcher))
}
} else {
consoleOnlyLogger.Warn().Msg("Event dispatcher not enabled. Please set ISLA_ENABLE_EVENT_DISPATCHER or ISLA_LOG_TO_EVENTQ to '1' to enable it.")
}
//TODO: default module to system
appLogger := log.New(appName, appConfig.GetString("LOG_LEVEL"), multiWriters)
//TODO: Need to wait till eventDispatcher is ready
time.Sleep(5 * time.Second)
app := App{Name: appName, Config: appConfig, log: *appLogger, eventDispatcher: appEventDispatcher}
err = app.initializeDB()
if err != nil {
consoleOnlyLogger.Fatal().Err(err).Msg("Failed to initialize database, exiting the application!!")
}
return &app
}
// New creates a new microApp
func New(appName string, appConfigDefaults map[string]interface{}, appLog zerolog.Logger, appDB *gorm.DB, appEventDispatcher event.Dispatcher) *App {
appConfig := config.NewConfig(appConfigDefaults)
return &App{Name: appName, Config: appConfig, log: appLog, DB: appDB, eventDispatcher: appEventDispatcher}
}
func (app *App) initializeDB() error {
var db *gorm.DB
err := retry.Do(3, time.Second*15, func() error {
var err error
db, err = gorm.Open("mysql", app.GetConnectionString())
if err != nil && strings.Contains(err.Error(), "connection refused") {
app.log.Warn().Msgf("Error connecting to Database [%v]. Trying again...", err)
return err
}
return retry.Stop{OriginalError: err}
})
app.DB = db
if strings.ToLower(app.Config.GetString("LOG_LEVEL")) == "trace" {
app.DB = app.DB.LogMode(true)
}
app.log.Info().Msg("Database connected!")
return err
}
// GetConnectionString gets database connection string
func (app *App) GetConnectionString() string {
dbHost := app.Config.GetString("DB_HOST")
dbName := app.Config.GetString("DB_NAME")
dbPort := app.Config.GetString("DB_PORT")
dbUser := app.Config.GetString("DB_USER")
dbPassword := app.Config.GetString("DB_PWD")
return fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?multiStatements=true&charset=utf8&parseTime=True&loc=Local", dbUser, dbPassword, dbHost, dbPort, dbName)
}
// NewUnitOfWork creates new UnitOfWork
func (app *App) NewUnitOfWork(readOnly bool) *repository.UnitOfWork {
return repository.NewUnitOfWork(app.DB, readOnly)
}
//Initialize initializes properties of the app
func (app *App) Initialize(routeSpecifiers []RouteSpecifier) {
logger := app.log
app.Router = mux.NewRouter()
app.Router.Use(mux.CORSMethodMiddleware(app.Router))
app.Router.Use(app.loggingMiddleware)
for _, routeSpecifier := range routeSpecifiers {
routeSpecifier.RegisterRoutes(app.Router)
}
//TODO: Revisit this logic
apiPort := "80"
if app.Config.IsSet("API_PORT") {
port := app.Config.GetString("API_PORT")
if _, err := strconv.Atoi(port); err != nil {
logger.Error().Msg("API port needs to be a number. " + port + " is not a number.")
} else {
apiPort = port
}
}
logger.Debug().Str("appname", app.Name).Msg("Api server will start on port: " + apiPort)
app.server = &http.Server{
Addr: "0.0.0.0:" + apiPort,
WriteTimeout: time.Second * time.Duration(app.Config.GetInt("HTTP_WRITE_TIMEOUT")),
ReadTimeout: time.Second * time.Duration(app.Config.GetInt("HTTP_READ_TIMEOUT")),
IdleTimeout: time.Second * time.Duration(app.Config.GetInt("HTTP_IDLE_TIMEOUT")),
Handler: app.Router,
}
}
//Start http server and start listening to the requests
func (app *App) Start() {
if err := app.server.ListenAndServe(); err != nil {
if err != http.ErrServerClosed {
app.log.Fatal().Err(err).Msg("Unable to start server, exiting the application!")
}
}
}
//StartSecure starts https server and listens to the requests
func (app *App) StartSecure(securityCert string, securityKey string) {
certFile := app.Config.GetString(securityCert)
if certFile == "" {
app.log.Fatal().Msg("Cert file could not be found, exiting the application!")
}
keyFile := app.Config.GetString(securityKey)
if certFile == "" {
app.log.Fatal().Msg("Key file could not be found, exiting the application!")
}
if err := app.server.ListenAndServeTLS(certFile, keyFile); err != nil {
app.log.Fatal().Err(err).Msg("Unable to start server or server stopped, exiting the application!")
}
}
// Logger returns logger for specified module
func (app *App) Logger(module string) *zerolog.Logger {
logger := app.log.With().Str("service", app.Name).Str("module", module).Logger()
return &logger
}
// MigrateDB Looks for migrations directory and runs the migrations scripts in that directory
func (app *App) MigrateDB() {
logger := app.log
logger.Debug().Msg("DB Migration Begin...")
fsrc, err := (&file.File{}).Open("file://migrations")
if err != nil {
logger.Info().Err(err).Msg("No migrations directory found, skipping migrations!")
logger.Info().Msg("DB Migration End!")
return
}
migrateDB, err := sql.Open("mysql", app.GetConnectionString())
if err != nil {
logger.Fatal().Err(err).Msg("Unable to open DB connection for migration, exiting the application!")
}
migrateDBDriver, err := mysql.WithInstance(migrateDB, &mysql.Config{})
if err != nil {
logger.Fatal().Err(err).Msg("Unable to prepare DB instance for migration, exiting the application!")
}
m, err := migrate.NewWithInstance("file", fsrc, "mysql", migrateDBDriver)
if err != nil {
logger.Fatal().Err(err).Msg("Unable to initialize DB instance for migration, exiting the application!")
}
err = m.Up()
if err != nil {
if err.Error() == "no change" {
logger.Info().Msg("DB already in latest state.")
} else {
logger.Fatal().Err(err).Msg("Failed to migrate DB, exiting the application!")
}
} else {
logger.Debug().Msg("Successfully upgraded DB")
}
logger.Info().Msg("DB Migration End!")
}
// Stop http server
func (app *App) Stop() {
wait, _ := time.ParseDuration("2m")
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
app.server.Shutdown(ctx)
app.DB.Close()
}
type httpStatusRecorder struct {
http.ResponseWriter
status int
}
func (rec *httpStatusRecorder) WriteHeader(code int) {
rec.status = code
rec.ResponseWriter.WriteHeader(code)
}
func (app *App) loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
if r.Header.Get("X-Correlation-ID") == "" {
r.Header.Set("X-Correlation-ID", uuid.NewV4().String())
}
logger := app.Logger("Ingress").With().Timestamp().Str("caller", r.Header.Get("X-Client")).Str("correlationId", r.Header.Get("X-Correlation-ID")).Str("method", r.Method).Str("requestURI", r.RequestURI).Logger()
rec := &httpStatusRecorder{ResponseWriter: w}
logger.Info().Msg("Begin")
next.ServeHTTP(rec, r)
if rec.status >= http.StatusInternalServerError {
logger.Error().Int("status", rec.status).Dur("responseTime", time.Now().Sub(startTime)).Msg("End.")
} else {
logger.Info().Int("status", rec.status).Dur("responseTime", time.Now().Sub(startTime)).Msg("End.")
}
})
}
// DispatchEvent delegates to eventDispatcher.
func (app *App) DispatchEvent(token string, corelationID string, topic string, payload interface{}) {
if app.eventDispatcher != nil {
app.eventDispatcher.DispatchEvent(token, corelationID, topic, payload)
}
}
// NewExecutionContext creates new exectuion context
func (app *App) NewExecutionContext(uow *repository.UnitOfWork, token *security.JwtToken, correlationID string, action string) microappCtx.ExecutionContext {
return microappCtx.NewExecutionContext(uow, token, correlationID, action, app.log)
}
// NewExecutionContextWithCustomToken creates new exectuion context with custom made token
func (app *App) NewExecutionContextWithCustomToken(uow *repository.UnitOfWork, tenantID uuid.UUID, userID uuid.UUID, username string, correlationID string, action string) microappCtx.ExecutionContext {
return microappCtx.NewExecutionContext(uow, &security.JwtToken{TenantID: tenantID, UserID: userID, UserName: username}, correlationID, action, app.log)
}
// NewExecutionContextWithSystemToken creates new exectuion context with sys default token
func (app *App) NewExecutionContextWithSystemToken(uow *repository.UnitOfWork, correlationID string, action string) microappCtx.ExecutionContext {
return microappCtx.NewExecutionContext(uow, &security.JwtToken{TenantID: uuid.Nil, UserID: uuid.Nil, TenantName: "None", UserName: "System", DisplayName: "System"}, correlationID, action, app.log)
}
// GetCorrelationIDFromRequest returns correlationId from request header
func GetCorrelationIDFromRequest(r *http.Request) string {
return r.Header.Get("X-Correlation-ID")
}