This repository has been archived by the owner on Mar 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
main.go
415 lines (360 loc) · 15.3 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package main
import (
"context"
"flag"
"net/http"
"os"
"os/signal"
"os/user"
"runtime"
"syscall"
"time"
"github.com/fabric8-services/fabric8-auth/app"
factorymanager "github.com/fabric8-services/fabric8-auth/application/factory/manager"
appservice "github.com/fabric8-services/fabric8-auth/application/service"
"github.com/fabric8-services/fabric8-auth/application/transaction"
accountservice "github.com/fabric8-services/fabric8-auth/authentication/account/service"
userworker "github.com/fabric8-services/fabric8-auth/authentication/account/worker"
stateworker "github.com/fabric8-services/fabric8-auth/authentication/provider/worker"
"github.com/fabric8-services/fabric8-auth/authorization/token/manager"
tokenworker "github.com/fabric8-services/fabric8-auth/authorization/token/worker"
"github.com/fabric8-services/fabric8-auth/configuration"
"github.com/fabric8-services/fabric8-auth/controller"
"github.com/fabric8-services/fabric8-auth/goamiddleware"
"github.com/fabric8-services/fabric8-auth/gormapplication"
"github.com/fabric8-services/fabric8-auth/jsonapi"
"github.com/fabric8-services/fabric8-auth/log"
"github.com/fabric8-services/fabric8-auth/metric"
"github.com/fabric8-services/fabric8-auth/migration"
"github.com/fabric8-services/fabric8-auth/worker"
"github.com/goadesign/goa"
goalogrus "github.com/goadesign/goa/logging/logrus"
"github.com/goadesign/goa/middleware"
"github.com/goadesign/goa/middleware/gzip"
"github.com/goadesign/goa/middleware/security/jwt"
"github.com/jinzhu/gorm"
"github.com/prometheus/client_golang/prometheus"
)
func main() {
// --------------------------------------------------------------------
// Parse flags
// --------------------------------------------------------------------
var configFile string
var serviceAccountConfigFile string
var printConfig bool
var migrateDB bool
flag.StringVar(&configFile, "config", "", "Path to the config file to read")
flag.StringVar(&serviceAccountConfigFile, "serviceAccountConfig", "", "Path to the service account configuration file")
flag.BoolVar(&printConfig, "printConfig", false, "Prints the config (including merged environment variables) and exits")
flag.BoolVar(&migrateDB, "migrateDatabase", false, "Migrates the database to the newest version and exits.")
flag.Parse()
// Override default -config switch with environment variable only if -config switch was
// not explicitly given via the command line.
configFile = configFileFromFlags("config", "AUTH_CONFIG_FILE_PATH")
serviceAccountConfigFile = configFileFromFlags("serviceAccountConfig", "AUTH_SERVICE_ACCOUNT_CONFIG_FILE")
config, err := configuration.NewConfigurationData(configFile, serviceAccountConfigFile)
if err != nil {
log.Panic(nil, map[string]interface{}{
"config_file": configFile,
"service_account_config_file": serviceAccountConfigFile,
"err": err,
}, "failed to setup the configuration")
}
if printConfig {
os.Exit(0)
}
// Initialized developer mode flag and log level for the logger
log.InitializeLogger(config.IsLogJSON(), config.GetLogLevel())
printUserInfo()
var db *gorm.DB
for {
db, err = gorm.Open("postgres", config.GetPostgresConfigString())
if err != nil {
db.Close()
log.Logger().Errorf("ERROR: Unable to open connection to database %v", err)
log.Logger().Infof("Retrying to connect in %v...", config.GetPostgresConnectionRetrySleep())
time.Sleep(config.GetPostgresConnectionRetrySleep())
} else {
break
}
}
// Initialize sentry client
// haltSentry, err := sentry.InitializeSentryClient(
// config.GetSentryDSN(),
// sentry.WithRelease(controller.Commit),
// sentry.WithEnvironment(config.GetEnvironment()),
// )
// if err != nil {
// log.Panic(nil, map[string]interface{}{
// "err": err,
// }, "failed to setup the sentry client")
// }
// defer haltSentry()
if config.IsPostgresDeveloperModeEnabled() && log.IsDebug() {
db = db.Debug()
}
if config.GetPostgresConnectionMaxIdle() > 0 {
log.Logger().Infof("Configured connection pool max idle %v", config.GetPostgresConnectionMaxIdle())
db.DB().SetMaxIdleConns(config.GetPostgresConnectionMaxIdle())
}
if config.GetPostgresConnectionMaxOpen() > 0 {
log.Logger().Infof("Configured connection pool max open %v", config.GetPostgresConnectionMaxOpen())
db.DB().SetMaxOpenConns(config.GetPostgresConnectionMaxOpen())
}
// Set the database transaction timeout
transaction.SetDatabaseTransactionTimeout(config.GetPostgresTransactionTimeout())
// Migrate the schema
err = migration.Migrate(db.DB(), config.GetPostgresDatabase(), config)
if err != nil {
log.Panic(nil, map[string]interface{}{
"err": err,
}, "failed migration")
}
// Nothing to here except exit, since the migration is already performed.
if migrateDB {
os.Exit(0)
}
// Create service
service := goa.New("auth")
// Mount middleware
service.Use(middleware.RequestID())
// Use our own log request to inject identity id and modify other properties
service.Use(log.LogRequest(config.IsPostgresDeveloperModeEnabled()))
service.Use(gzip.Middleware(9))
service.Use(jsonapi.ErrorHandler(service, true))
service.Use(middleware.Recover())
service.WithLogger(goalogrus.New(log.Logger()))
// Setup Account/Login/Security
appDB := gormapplication.NewGormDB(db, config, factorymanager.NewDisabledFactoryWrappers())
tokenManager, err := manager.DefaultManager(config)
if err != nil {
log.Panic(nil, map[string]interface{}{
"err": err,
}, "failed to create token manager")
}
// Middleware that extracts and stores the token in the context
jwtMiddlewareTokenContext := goamiddleware.TokenContext(appDB, tokenManager, app.NewJWTSecurity())
service.Use(jwtMiddlewareTokenContext)
service.Use(manager.InjectTokenManager(tokenManager))
service.Use(log.LogRequest(config.IsPostgresDeveloperModeEnabled()))
app.UseJWTMiddleware(service, jwt.New(tokenManager.PublicKeys(), nil, app.NewJWTSecurity()))
var tenantService appservice.TenantService
if config.GetTenantServiceURL() != "" {
log.Logger().Infof("Enabling Tenant service %v", config.GetTenantServiceURL())
tenantService = accountservice.NewTenantService(config)
} else {
log.Logger().Warn("Tenant service is not enabled")
}
// Try to fetch the initial list of clusters and start Cluster Service cache refresher
_, err = appDB.ClusterService().Status(context.Background(), func(c *http.Client) {
c.Timeout = 3 * time.Second
})
if err != nil {
// It's not a critical error. Cluster management service can be offline during Auth service startup.
// Cluster service during startup requires Auth service to be ready to fetch public keys.
// So, we can't introduce cycle dependency in Auth service startup on Cluster service.
// If fetching clusters upfront failed in main function then let's just log this error and continue to start the service.
// We will try to fetch clusters later when we need them during user registration or OSO-OSIO account linking.
log.Warn(nil, map[string]interface{}{
"err": err,
}, "failed to fetch clusters")
}
// Mount "login" controller
loginCtrl := controller.NewLoginController(service, appDB)
app.MountLoginController(service, loginCtrl)
// Mount "resource-roles" controller
resourceRoleCtrl := controller.NewResourceRolesController(service, appDB)
app.MountResourceRolesController(service, resourceRoleCtrl)
// Mount "roles" controller
rolesCtrl := controller.NewRolesController(service, appDB)
app.MountRolesController(service, rolesCtrl)
// Mount "authorize" controller
authorizeCtrl := controller.NewAuthorizeController(service, appDB, config)
app.MountAuthorizeController(service, authorizeCtrl)
// Mount "logout" controller
logoutCtrl := controller.NewLogoutController(service, appDB)
app.MountLogoutController(service, logoutCtrl)
// Mount "token" controller
tokenCtrl := controller.NewTokenController(service, appDB, tokenManager, config)
app.MountTokenController(service, tokenCtrl)
// Mount "status" controller
statusCtrl := controller.NewStatusController(service, controller.NewGormDBChecker(db), config)
app.MountStatusController(service, statusCtrl)
// Mount "space" controller
spaceCtrl := controller.NewSpaceController(service, appDB)
app.MountSpaceController(service, spaceCtrl)
// Mount "open-configuration" controller
openidConfigurationCtrl := controller.NewOpenidConfigurationController(service)
app.MountOpenidConfigurationController(service, openidConfigurationCtrl)
// Mount "user" controller
userCtrl := controller.NewUserController(service, appDB, config, tokenManager, tenantService)
app.MountUserController(service, userCtrl)
// Mount "search" controller
searchCtrl := controller.NewSearchController(service, appDB, config)
app.MountSearchController(service, searchCtrl)
// Mount "users" controller
emailVerificationService := accountservice.NewEmailVerificationClient(appDB)
usersCtrl := controller.NewUsersController(service, appDB, config)
usersCtrl.EmailVerificationService = emailVerificationService
app.MountUsersController(service, usersCtrl)
// Mount "namedusers" controlller
namedusersCtrl := controller.NewNamedusersController(service, appDB, config, tenantService)
app.MountNamedusersController(service, namedusersCtrl)
//Mount "userinfo" controller
userInfoCtrl := controller.NewUserinfoController(service, appDB, tokenManager)
app.MountUserinfoController(service, userInfoCtrl)
// Mount the user service controller
userServiceCtrl := controller.NewUserServiceController(service, appDB)
app.MountUserServiceController(service, userServiceCtrl)
// Mount "collaborators" controller
collaboratorsCtrl := controller.NewCollaboratorsController(service, appDB, config)
app.MountCollaboratorsController(service, collaboratorsCtrl)
// Mount "clusters" controller
clustersCtrl := controller.NewClustersController(service, config)
app.MountClustersController(service, clustersCtrl)
// Mount "resources" controller
resourcesCtrl := controller.NewResourceController(service, appDB)
app.MountResourceController(service, resourcesCtrl)
// Mount "organizations" controller
organizationCtrl := controller.NewOrganizationController(service, appDB)
app.MountOrganizationController(service, organizationCtrl)
// Mount "teams" controller
teamCtrl := controller.NewTeamController(service, appDB)
app.MountTeamController(service, teamCtrl)
// Mount "invitations" controller
invitationCtrl := controller.NewInvitationController(service, appDB, config)
app.MountInvitationController(service, invitationCtrl)
log.Logger().Infoln("Git Commit SHA: ", controller.Commit)
log.Logger().Infoln("UTC Build Time: ", controller.BuildTime)
log.Logger().Infoln("UTC Start Time: ", controller.StartTime)
log.Logger().Infoln("Dev mode: ", config.IsPostgresDeveloperModeEnabled())
log.Logger().Infoln("GOMAXPROCS: ", runtime.GOMAXPROCS(-1))
log.Logger().Infoln("NumCPU: ", runtime.NumCPU())
http.Handle("/api/", service.Mux)
http.Handle("/favicon.ico", http.NotFoundHandler())
// Start/mount metrics http
if config.GetHTTPAddress() == config.GetMetricsHTTPAddress() {
http.Handle("/metrics", prometheus.Handler())
} else {
go func(metricAddress string) {
mx := http.NewServeMux()
mx.Handle("/metrics", prometheus.Handler())
if err := http.ListenAndServe(metricAddress, mx); err != nil {
log.Error(nil, map[string]interface{}{
"addr": metricAddress,
"err": err,
}, "unable to connect to metrics server")
service.LogError("startup", "err", err)
}
}(config.GetMetricsHTTPAddress())
}
// register user deactivation prometheus metric
metric.RegisterMetrics()
// Start background workers
// token cleanup, running once every hour
tokenCleanupWorker := tokenworker.NewTokenCleanupWorker(context.Background(), appDB)
tokenCleanupWorker.Start(time.Hour)
workers := []Worker{tokenCleanupWorker}
// User deactivation and notification workers
ctx := manager.ContextWithTokenManager(context.Background(), tokenManager)
ctx = context.WithValue(ctx, worker.LockOwner, config.GetPodName())
if config.GetUserDeactivationNotificationEnabled() {
log.Info(nil, map[string]interface{}{
"user_fetch_limit": config.GetUserDeactivationFetchLimit(),
"inactivity_notification_period": config.GetUserDeactivationInactivityNotificationPeriod(),
"notification_interval": config.GetUserDeactivationNotificationWorkerInterval(),
}, "Deactivation notification worker enabled")
userDeactivationNotificationWorker := userworker.NewUserDeactivationNotificationWorker(ctx, appDB)
userDeactivationNotificationWorker.Start(config.GetUserDeactivationNotificationWorkerInterval())
workers = append(workers, userDeactivationNotificationWorker)
}
if config.GetUserDeactivationEnabled() {
log.Info(nil, map[string]interface{}{
"user_fetch_limit": config.GetUserDeactivationFetchLimit(),
"inactivity_period": config.GetUserDeactivationInactivityPeriod(),
"deactivation_interval": config.GetUserDeactivationWorkerInterval(),
}, "Deactivation worker enabled")
userDeactivationWorker := userworker.NewUserDeactivationWorker(ctx, appDB)
userDeactivationWorker.Start(config.GetUserDeactivationWorkerInterval())
workers = append(workers, userDeactivationWorker)
}
if config.GetOAuthStateReferencesCleanupEnabled() {
log.Info(nil, map[string]interface{}{
"cleanup_interval": config.GetOAuthStateReferencesCleanupWorkerInterval(),
}, "OAuthStateReferences cleanup worker enabled")
oauthStateReferenceCleanupWorker := stateworker.NewOAuthStateReferenceCleanupWorker(ctx, appDB)
oauthStateReferenceCleanupWorker.Start(config.GetOAuthStateReferencesCleanupWorkerInterval())
workers = append(workers, oauthStateReferenceCleanupWorker)
}
// graceful shutdown
go handleShutdown(db, workers...)
// Start http
if err := http.ListenAndServe(config.GetHTTPAddress(), nil); err != nil {
log.Error(nil, map[string]interface{}{
"addr": config.GetHTTPAddress(),
"err": err,
}, "unable to connect to server")
service.LogError("startup", "err", err)
}
}
type Worker interface {
Start(freq time.Duration)
Stop()
}
func handleShutdown(db *gorm.DB, workers ...Worker) {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
// handle ctrl+c event here
// close database
log.Warn(nil, nil, "Closing DB connection before complete shutdown")
err := db.Close()
if err != nil {
log.Error(nil, map[string]interface{}{
"error": err,
}, "error while closing the connection to the database")
}
// also, stop the workers
for _, w := range workers {
w.Stop()
}
os.Exit(0)
}
func configFileFromFlags(flagName string, envVarName string) string {
configSwitchIsSet := false
flag.Visit(func(f *flag.Flag) {
if f.Name == flagName {
configSwitchIsSet = true
}
})
if !configSwitchIsSet {
if envConfigPath, ok := os.LookupEnv(envVarName); ok {
return envConfigPath
}
}
return ""
}
func printUserInfo() {
u, err := user.Current()
if err != nil {
log.Warn(nil, map[string]interface{}{
"err": err,
}, "failed to get current user")
} else {
log.Info(nil, map[string]interface{}{
"username": u.Username,
"uuid": u.Uid,
}, "Running as user name '%s' with UID %s.", u.Username, u.Uid)
g, err := user.LookupGroupId(u.Gid)
if err != nil {
log.Warn(nil, map[string]interface{}{
"err": err,
}, "failed to lookup group")
} else {
log.Info(nil, map[string]interface{}{
"groupname": g.Name,
"gid": g.Gid,
}, "Running as as group '%s' with GID %s.", g.Name, g.Gid)
}
}
}