-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.go
More file actions
281 lines (228 loc) · 8.8 KB
/
main.go
File metadata and controls
281 lines (228 loc) · 8.8 KB
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
package main
import (
"context"
"database/sql"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/fiware/VCVerifier/ccsapi"
configModel "github.com/fiware/VCVerifier/config"
"github.com/fiware/VCVerifier/database"
logging "github.com/fiware/VCVerifier/logging"
api "github.com/fiware/VCVerifier/openapi"
"github.com/fiware/VCVerifier/verifier"
"github.com/foolin/goview/supports/ginview"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/penglongli/gin-metrics/ginmetrics"
)
// default config file location - can be overwritten by envvar
var configFile string = "server.yaml"
// main is the startup method that configures and runs the verifier HTTP server.
// When the config server is enabled, it also starts a second HTTP server for the
// Credentials Config Service (CCS) REST API on a separate port.
func main() {
configuration, err := configModel.ReadConfig(configFile)
if err != nil {
panic(err)
}
logging.Configure(configuration.Logging)
logger := logging.Log()
logger.Infof("Configuration is: %s", logging.PrettyPrintObject(configuration))
// --- Optional: Database and Config Server initialization ---
var db *sql.DB
var configSrv *http.Server
var repo database.ServiceRepository
if configuration.ConfigServer.Enabled {
db, configSrv, repo, err = initConfigServer(&configuration)
if err != nil {
logger.Errorf("Failed to initialize config server: %v", err)
panic(err)
}
defer database.Close(db)
}
verifier.InitVerifier(&configuration, repo)
verifier.InitPresentationParser(&configuration, Health())
router := getRouter()
// health check
router.GET("/health", HealthReq)
allowedOrigins := ResolveAllowedOrigins(configuration.ConfigRepo.Services)
logger.Infof("CORS allowed origins: %v", allowedOrigins)
router.Use(cors.New(cors.Config{
AllowOrigins: allowedOrigins,
AllowMethods: []string{"POST", "GET"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
AllowCredentials: true,
}))
//new template engine
router.HTMLRender = ginview.Default()
// static files for the frontend
router.Static("/static", configuration.Server.StaticDir)
templateDir := configuration.Server.TemplateDir
if templateDir != "" {
if strings.HasSuffix(templateDir, "/") {
templateDir = templateDir + "*.html"
} else {
templateDir = templateDir + "/*.html"
}
logging.Log().Infof("Intialize templates from %s", templateDir)
router.LoadHTMLGlob(templateDir)
}
// initiate metrics
metrics := ginmetrics.GetMonitor()
metrics.SetMetricPath("/metrics")
metrics.Use(router)
srv := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%v", configuration.Server.Port),
Handler: router,
ReadTimeout: time.Duration(configuration.Server.ReadTimeout) * time.Second,
WriteTimeout: time.Duration(configuration.Server.WriteTimeout) * time.Second,
IdleTimeout: time.Duration(configuration.Server.IdleTimeout) * time.Second,
}
// Start the verifier server in a goroutine so it doesn't block
go func() {
logging.Log().Infof("Starting verifier server on port %v", configuration.Server.Port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logging.Log().Errorf("Failed to start verifier server: %v", err)
os.Exit(1)
}
}()
// Start the config server if enabled
if configSrv != nil {
go func() {
logging.Log().Infof("Starting config server on port %v", configuration.ConfigServer.Port)
if err := configSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logging.Log().Errorf("Failed to start config server: %v", err)
os.Exit(1)
}
}()
}
// --- Graceful Shutdown Logic ---
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
logging.Log().Info("Shutting down servers...")
shutdownTimeout := time.Duration(configuration.Server.ShutdownTimeout) * time.Second
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
// Shut down the config server first (if running)
if configSrv != nil {
logging.Log().Info("Shutting down config server...")
if err := configSrv.Shutdown(ctx); err != nil {
logging.Log().Errorf("Config server forced to shutdown: %v", err)
}
logging.Log().Info("Config server stopped")
}
// Shut down the verifier server
if err := srv.Shutdown(ctx); err != nil {
logging.Log().Errorf("Verifier server forced to shutdown: %v", err)
}
logging.Log().Info("All servers exiting gracefully")
}
// initConfigServer opens a database connection, initializes the schema, creates
// a service repository, and builds the CCS API HTTP server. Returns the database
// connection (for deferred close), the config HTTP server (to be started by the
// caller), the service repository (for verifier integration), or an error if
// setup fails.
func initConfigServer(configuration *configModel.Configuration) (*sql.DB, *http.Server, database.ServiceRepository, error) {
logger := logging.Log()
logger.Info("Initializing database connection for config server...")
db, err := database.NewConnection(configuration.Database)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to open database connection: %w", err)
}
logger.Info("Initializing database schema...")
if err := database.InitSchema(db, configuration.Database.Type); err != nil {
database.Close(db)
return nil, nil, nil, fmt.Errorf("failed to initialize database schema: %w", err)
}
repo := database.NewServiceRepository(db, configuration.Database.Type)
configRouter := getConfigRouter(db, repo)
cfgSrv := configuration.ConfigServer
srv := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%v", cfgSrv.Port),
Handler: configRouter,
ReadTimeout: time.Duration(cfgSrv.ReadTimeout) * time.Second,
WriteTimeout: time.Duration(cfgSrv.WriteTimeout) * time.Second,
IdleTimeout: time.Duration(cfgSrv.IdleTimeout) * time.Second,
}
logger.Infof("Config server configured on port %v", cfgSrv.Port)
return db, srv, repo, nil
}
// getConfigRouter creates a Gin router for the CCS API with health check,
// CORS middleware, and all CCS service routes registered.
func getConfigRouter(db *sql.DB, repo database.ServiceRepository) *gin.Engine {
writer := logging.GetGinInternalWriter()
gin.DefaultWriter = writer
gin.DefaultErrorWriter = writer
router := gin.New()
router.Use(logging.GinHandlerFunc(), gin.Recovery())
// CORS - allow all origins for API compatibility; must be registered before routes
router.Use(cors.New(cors.Config{
AllowAllOrigins: true,
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
}))
// Health check with database ping
configHealth := NewConfigServerHealth(db)
router.GET("/health", ConfigServerHealthReq(configHealth))
// Register CCS API routes
ccsapi.RegisterRoutes(router, repo)
return router
}
// initiate the router
func getRouter() *gin.Engine {
// the openapi generated router uses the defaults, which we want to override to improve and configure logging
writer := logging.GetGinInternalWriter()
gin.DefaultWriter = writer
gin.DefaultErrorWriter = writer
router := gin.New()
router.Use(logging.GinHandlerFunc(), gin.Recovery())
for _, route := range api.NewRouter().Routes() {
router.Handle(route.Method, route.Path, route.HandlerFunc)
}
return router
}
// allow override of the config-file on init. Everything else happens on main to improve testability
func init() {
configFileEnv := os.Getenv("CONFIG_FILE")
if configFileEnv != "" {
configFile = configFileEnv
}
logging.Log().Infof("Will read config from %s", configFile)
}
// wildcardOrigin is the CORS origin value that permits requests from any origin.
const wildcardOrigin = "*"
// ResolveAllowedOrigins aggregates the AllowedOrigins from all configured
// services into a deduplicated list of CORS origins. The rules are:
//
// - If no services are provided, or none of them specify any AllowedOrigins,
// the function returns ["*"] (wildcard) for backward compatibility.
// - If any service includes "*" in its AllowedOrigins, the function returns
// ["*"] because the wildcard takes precedence over specific origins.
// - Otherwise the function returns the deduplicated union of all origins.
func ResolveAllowedOrigins(services []configModel.ConfiguredService) []string {
seen := make(map[string]struct{})
var origins []string
for _, svc := range services {
for _, origin := range svc.AllowedOrigins {
if origin == wildcardOrigin {
// Wildcard takes precedence — no need to collect further.
return []string{wildcardOrigin}
}
if _, exists := seen[origin]; !exists {
seen[origin] = struct{}{}
origins = append(origins, origin)
}
}
}
// No origins configured at all — default to wildcard for backward compatibility.
if len(origins) == 0 {
return []string{wildcardOrigin}
}
return origins
}