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 29
/
main.go
249 lines (213 loc) · 7.84 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
package main
import (
"flag"
"fmt"
"net/http"
"os"
"time"
"github.com/fabric8-services/fabric8-tenant/metric"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/fabric8-services/fabric8-common/log"
"github.com/fabric8-services/fabric8-tenant/app"
"github.com/fabric8-services/fabric8-tenant/auth"
"github.com/fabric8-services/fabric8-tenant/cluster"
"github.com/fabric8-services/fabric8-tenant/configuration"
"github.com/fabric8-services/fabric8-tenant/controller"
"github.com/fabric8-services/fabric8-tenant/environment"
"github.com/fabric8-services/fabric8-tenant/jsonapi"
"github.com/fabric8-services/fabric8-tenant/migration"
"github.com/fabric8-services/fabric8-tenant/tenant"
"github.com/fabric8-services/fabric8-tenant/toggles"
"github.com/fabric8-services/fabric8-tenant/update"
witmiddleware "github.com/fabric8-services/fabric8-wit/goamiddleware"
"github.com/goadesign/goa"
"github.com/goadesign/goa/logging/logrus"
"github.com/goadesign/goa/middleware"
"github.com/goadesign/goa/middleware/gzip"
goajwt "github.com/goadesign/goa/middleware/security/jwt"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
func main() {
viper.GetStringMapString("TEST")
var migrateDB bool
flag.BoolVar(&migrateDB, "migrateDatabase", false, "Migrates the database to the newest version and exits.")
flag.Parse()
// Initialized configuration
config, err := configuration.GetData()
if err != nil {
logrus.Panic(nil, map[string]interface{}{
"err": err,
}, "failed to setup the configuration")
}
errorMsg := checkTemplateVersions()
if errorMsg != "" {
log.Panic(nil, map[string]interface{}{}, errorMsg)
}
db := connect(config)
defer db.Close()
migrate(db)
// Nothing to here except exit, since the migration is already performed.
if migrateDB {
os.Exit(0)
}
toggles.Init("f8tenant", config.GetTogglesURL())
authService, err := auth.NewAuthService(config)
if err != nil {
log.Panic(nil, map[string]interface{}{
"err": err,
}, "failed to initialize the auth.Service component")
}
publicKeys, err := authService.GetPublicKeys()
if err != nil {
log.Panic(nil, map[string]interface{}{
"err": err,
"target": config.GetAuthURL(),
}, "failed to fetch public keys from token service")
}
// Create service
service := goa.New("tenant")
// Mount middleware
service.WithLogger(goalogrus.New(log.Logger()))
service.Use(middleware.RequestID())
service.Use(gzip.Middleware(9))
service.Use(jsonapi.ErrorHandler(service, true))
service.Use(middleware.Recover())
service.Use(witmiddleware.TokenContext(publicKeys, nil, app.NewJWTSecurity()))
service.Use(log.LogRequest(config.IsDeveloperModeEnabled()))
app.UseJWTMiddleware(service, goajwt.New(publicKeys, nil, app.NewJWTSecurity()))
clusterService := cluster.NewClusterService(config.GetClustersRefreshDelay(), authService)
err = clusterService.Start()
if err != nil {
log.Panic(nil, map[string]interface{}{
"err": err,
}, "failed to initialize the cluster.Service component")
}
defer clusterService.Stop()
//haltSentry, err := sentry.InitializeLogger(config, configuration.Commit)
//if err != nil {
// log.Panic(nil, map[string]interface{}{
// "err": err,
// }, "failed to setup the sentry client")
//}
//defer haltSentry()
// register prometheus metrics
metric.RegisterMetrics()
tenantService := tenant.NewDBService(db)
tenantUpdater := controller.TenantUpdater{
Config: config,
TenantService: tenantService,
ClusterService: clusterService,
}
// Check & do all tenants update
if config.IsAutomatedUpdateEnabled() {
log.Info(nil, map[string]interface{}{}, "automated update is enabled")
go update.NewTenantsUpdater(db, config, clusterService, tenantUpdater, update.AllTypes, "").UpdateAllTenants()
} else {
log.Info(nil, map[string]interface{}{}, "automated update is disabled")
}
// Mount "status" controller
statusCtrl := controller.NewStatusController(service, db)
app.MountStatusController(service, statusCtrl)
// Mount "tenant" controller
tenantCtrl := controller.NewTenantController(service, tenantService, clusterService, authService, config)
app.MountTenantController(service, tenantCtrl)
tenantsCtrl := controller.NewTenantsController(service, tenantService, clusterService, authService, config)
app.MountTenantsController(service, tenantsCtrl)
// Mount "update" controller
updateCtrl := controller.NewUpdateController(service, db, config, clusterService, tenantUpdater)
app.MountUpdateController(service, updateCtrl)
log.Logger().Infoln("Git Commit SHA: ", configuration.Commit)
log.Logger().Infoln("UTC Build Time: ", configuration.BuildTime)
log.Logger().Infoln("UTC Start Time: ", configuration.StartTime)
log.Logger().Infoln("Dev mode: ", config.IsDeveloperModeEnabled())
log.Logger().Infoln("Auth URL: ", config.GetAuthURL())
http.Handle("/favicon.ico", http.NotFoundHandler())
http.Handle("/", service.Mux)
// Start/mount metrics http
if config.GetHTTPAddress() == config.GetMetricsHTTPAddress() {
http.Handle("/metrics", promhttp.Handler())
} else {
go func(metricAddress string) {
mx := http.NewServeMux()
mx.Handle("/metrics", promhttp.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())
}
// 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)
}
}
func checkTemplateVersions() string {
errorMsg := ""
if environment.VersionFabric8TenantUserFile == "" {
errorMsg = errorMsg + createNotSetVersionError("VersionFabric8TenantUserFile")
} else {
logVersionInfo("fabric8-tenant-user.yml", environment.VersionFabric8TenantUserFile)
}
if environment.VersionFabric8TenantCheMtFile == "" {
errorMsg = errorMsg + createNotSetVersionError("VersionFabric8TenantCheMtFile")
} else {
logVersionInfo("fabric8-tenant-che-mt.yml", environment.VersionFabric8TenantCheMtFile)
}
if environment.VersionFabric8TenantCheQuotasFile == "" {
errorMsg = errorMsg + createNotSetVersionError("VersionFabric8TenantCheQuotasFile")
} else {
logVersionInfo("fabric8-tenant-che-quotas.yml", environment.VersionFabric8TenantCheQuotasFile)
}
return errorMsg
}
func createNotSetVersionError(variable string) string {
return fmt.Sprintf("The variable %s representing a template version is not set.\n", variable)
}
func logVersionInfo(target, version string) {
log.Logger().Infof("Using %s of version: %s", target, version)
}
func connect(config *configuration.Data) *gorm.DB {
var err error
var db *gorm.DB
for {
db, err = gorm.Open("postgres", config.GetPostgresConfigString())
if err != nil {
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
}
}
if config.IsDeveloperModeEnabled() {
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())
}
return db
}
func migrate(db *gorm.DB) {
// Migrate the schema
err := migration.Migrate(db.DB())
if err != nil {
log.Panic(nil, map[string]interface{}{
"err": err,
}, "failed migration")
}
}