MCPcopy
hub / github.com/crowdsecurity/crowdsec / NewServer

Function NewServer

pkg/apiserver/apiserver.go:118–245  ·  view source on GitHub ↗

NewServer creates a LAPI server. It sets up a gin router, a database client, and a controller.

(ctx context.Context, config *csconfig.LocalApiServerCfg, accessLogger *log.Entry)

Source from the content-addressed store, hash-verified

116// NewServer creates a LAPI server.
117// It sets up a gin router, a database client, and a controller.
118func NewServer(ctx context.Context, config *csconfig.LocalApiServerCfg, accessLogger *log.Entry) (*APIServer, error) {
119 var flushScheduler gocron.Scheduler
120
121 if accessLogger == nil {
122 accessLogger = log.StandardLogger().WithFields(nil)
123 }
124
125 dbClient, err := database.NewClient(ctx, config.DbConfig, config.DbConfig.NewLogger())
126 if err != nil {
127 return nil, fmt.Errorf("unable to init database client: %w", err)
128 }
129
130 if config.DbConfig.Flush != nil {
131 flushScheduler, err = dbClient.StartFlushScheduler(ctx, config.DbConfig.Flush)
132 if err != nil {
133 return nil, err
134 }
135 }
136
137 if !log.IsLevelEnabled(log.DebugLevel) {
138 gin.SetMode(gin.ReleaseMode)
139 }
140
141 router := gin.New()
142
143 router.ForwardedByClientIP = false
144
145 // set the remore address of the request to 127.0.0.1 if it comes from a unix socket
146 router.Use(func(c *gin.Context) {
147 if c.Request.RemoteAddr == "@" {
148 c.Request.RemoteAddr = "127.0.0.1:65535"
149 }
150 })
151
152 if config.TrustedProxies != nil && config.UseForwardedForHeaders {
153 if err = router.SetTrustedProxies(*config.TrustedProxies); err != nil {
154 return nil, fmt.Errorf("while setting trusted_proxies: %w", err)
155 }
156
157 router.ForwardedByClientIP = true
158 }
159
160 gin.DefaultErrorWriter = accessLogger.WriterLevel(log.ErrorLevel)
161 gin.DefaultWriter = accessLogger.Writer()
162
163 router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
164 return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s %q %s\"\n",
165 param.ClientIP,
166 param.TimeStamp.Format(time.RFC1123),
167 param.Method,
168 param.Path,
169 param.Request.Proto,
170 param.StatusCode,
171 param.Latency,
172 param.Request.UserAgent(),
173 param.ErrorMessage,
174 )
175 }))

Callers 6

initAPIServerFunction · 0.92
NewAPIServerFunction · 0.85
NewAPITestForwardedForFunction · 0.85
TestWithWrongDBConfigFunction · 0.85
TestWithWrongFlushConfigFunction · 0.85

Calls 13

StartFlushSchedulerMethod · 0.95
NewClientFunction · 0.92
SubLoggerFunction · 0.92
NewAPICFunction · 0.85
NewPAPIFunction · 0.85
StandardLoggerMethod · 0.80
IsEnrolledMethod · 0.80
GetTrustedIPsMethod · 0.80
ErrorMethod · 0.65
NewLoggerMethod · 0.45
UseMethod · 0.45
FormatMethod · 0.45

Tested by 5

NewAPIServerFunction · 0.68
NewAPITestForwardedForFunction · 0.68
TestWithWrongDBConfigFunction · 0.68
TestWithWrongFlushConfigFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…