forked from rudderlabs/rudder-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
420 lines (359 loc) · 12.6 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
416
417
418
419
420
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/rudderlabs/rudder-server/warehouse/deltalake"
"runtime/pprof"
"strconv"
"strings"
"net/http"
"os"
"os/signal"
"runtime"
"syscall"
"time"
"github.com/bugsnag/bugsnag-go/v2"
"github.com/gorilla/mux"
_ "go.uber.org/automaxprocs"
"golang.org/x/sync/errgroup"
"github.com/rudderlabs/rudder-server/gateway"
"github.com/rudderlabs/rudder-server/gateway/webhook"
"github.com/rudderlabs/rudder-server/jobsdb"
operationmanager "github.com/rudderlabs/rudder-server/operation-manager"
"github.com/rudderlabs/rudder-server/processor"
"github.com/rudderlabs/rudder-server/processor/integrations"
"github.com/rudderlabs/rudder-server/processor/stash"
"github.com/rudderlabs/rudder-server/processor/transformer"
ratelimiter "github.com/rudderlabs/rudder-server/rate-limiter"
"github.com/rudderlabs/rudder-server/router"
"github.com/rudderlabs/rudder-server/router/batchrouter"
"github.com/rudderlabs/rudder-server/router/batchrouter/asyncdestinationmanager"
"github.com/rudderlabs/rudder-server/router/customdestinationmanager"
oauth "github.com/rudderlabs/rudder-server/router/oauthResponseHandler"
routertransformer "github.com/rudderlabs/rudder-server/router/transformer"
batchrouterutils "github.com/rudderlabs/rudder-server/router/utils"
event_schema "github.com/rudderlabs/rudder-server/event-schema"
"github.com/rudderlabs/rudder-server/admin"
"github.com/rudderlabs/rudder-server/admin/profiler"
"github.com/rudderlabs/rudder-server/app"
"github.com/rudderlabs/rudder-server/app/apphandlers"
"github.com/rudderlabs/rudder-server/config"
backendconfig "github.com/rudderlabs/rudder-server/config/backend-config"
"github.com/rudderlabs/rudder-server/rruntime"
"github.com/rudderlabs/rudder-server/services/alert"
"github.com/rudderlabs/rudder-server/services/archiver"
"github.com/rudderlabs/rudder-server/services/db"
destinationdebugger "github.com/rudderlabs/rudder-server/services/debugger/destination"
sourcedebugger "github.com/rudderlabs/rudder-server/services/debugger/source"
transformationdebugger "github.com/rudderlabs/rudder-server/services/debugger/transformation"
"github.com/rudderlabs/rudder-server/services/dedup"
"github.com/rudderlabs/rudder-server/services/streammanager/kafka"
destination_connection_tester "github.com/rudderlabs/rudder-server/services/destination-connection-tester"
"github.com/rudderlabs/rudder-server/services/diagnostics"
"github.com/rudderlabs/rudder-server/services/pgnotifier"
"github.com/rudderlabs/rudder-server/services/stats"
"github.com/rudderlabs/rudder-server/utils/logger"
"github.com/rudderlabs/rudder-server/utils/misc"
"github.com/rudderlabs/rudder-server/utils/types"
azuresynapse "github.com/rudderlabs/rudder-server/warehouse/azure-synapse"
"github.com/rudderlabs/rudder-server/warehouse/bigquery"
"github.com/rudderlabs/rudder-server/warehouse/mssql"
"github.com/rudderlabs/rudder-server/warehouse/postgres"
"github.com/rudderlabs/rudder-server/warehouse/redshift"
"github.com/rudderlabs/rudder-server/warehouse/snowflake"
warehouseutils "github.com/rudderlabs/rudder-server/warehouse/utils"
"github.com/rudderlabs/rudder-server/warehouse"
"github.com/rudderlabs/rudder-server/warehouse/clickhouse"
// This is necessary for compatibility with enterprise features
_ "github.com/rudderlabs/rudder-server/imports"
)
var (
application app.Interface
warehouseMode string
enableSuppressUserFeature bool
pkgLogger logger.LoggerI
appHandler apphandlers.AppHandler
ReadTimeout time.Duration
ReadHeaderTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
gracefulShutdownTimeout time.Duration
MaxHeaderBytes int
)
var version = "Not an official release. Get the latest release from the github repo."
var major, minor, commit, buildDate, builtBy, gitURL, patch string
func loadConfig() {
config.RegisterStringConfigVariable("embedded", &warehouseMode, false, "Warehouse.mode")
config.RegisterBoolConfigVariable(true, &enableSuppressUserFeature, false, "Gateway.enableSuppressUserFeature")
config.RegisterDurationConfigVariable(time.Duration(0), &ReadTimeout, false, time.Second, []string{"ReadTimeOut", "ReadTimeOutInSec"}...)
config.RegisterDurationConfigVariable(time.Duration(0), &ReadHeaderTimeout, false, time.Second, []string{"ReadHeaderTimeout", "ReadHeaderTimeoutInSec"}...)
config.RegisterDurationConfigVariable(time.Duration(10), &WriteTimeout, false, time.Second, []string{"WriteTimeout", "WriteTimeOutInSec"}...)
config.RegisterDurationConfigVariable(time.Duration(720), &IdleTimeout, false, time.Second, []string{"IdleTimeout", "IdleTimeoutInSec"}...)
config.RegisterDurationConfigVariable(time.Duration(15), &gracefulShutdownTimeout, false, time.Second, "GracefulShutdownTimeout")
config.RegisterIntConfigVariable(524288, &MaxHeaderBytes, false, 1, "MaxHeaderBytes")
}
func Init() {
loadConfig()
pkgLogger = logger.NewLogger().Child("main")
}
func versionInfo() map[string]interface{} {
return map[string]interface{}{"Version": version, "Major": major, "Minor": minor, "Patch": patch, "Commit": commit, "BuildDate": buildDate, "BuiltBy": builtBy, "GitUrl": gitURL, "TransformerVersion": transformer.GetVersion(), "DatabricksVersion": misc.GetDatabricksVersion()}
}
func versionHandler(w http.ResponseWriter, r *http.Request) {
var version = versionInfo()
versionFormatted, _ := json.Marshal(&version)
w.Write(versionFormatted)
}
func printVersion() {
version := versionInfo()
versionFormatted, _ := json.MarshalIndent(&version, "", " ")
fmt.Printf("Version Info %s\n", versionFormatted)
}
func startWarehouseService(ctx context.Context, application app.Interface) error {
return warehouse.Start(ctx, application)
}
func canStartServer() bool {
pkgLogger.Info("warehousemode ", warehouseMode)
return warehouseMode == config.EmbeddedMode || warehouseMode == config.OffMode || warehouseMode == config.PooledWHSlaveMode
}
func canStartWarehouse() bool {
return warehouseMode != config.OffMode
}
func runAllInit() {
config.Load()
admin.Init()
app.Init()
logger.Init()
misc.Init()
stats.Init()
db.Init()
diagnostics.Init()
backendconfig.Init()
warehouseutils.Init()
bigquery.Init()
clickhouse.Init()
archiver.Init()
destinationdebugger.Init()
pgnotifier.Init()
jobsdb.Init()
jobsdb.Init2()
jobsdb.Init3()
destination_connection_tester.Init()
warehouse.Init()
warehouse.Init2()
warehouse.Init3()
warehouse.Init4()
warehouse.Init5()
warehouse.Init6()
azuresynapse.Init()
mssql.Init()
postgres.Init()
redshift.Init()
snowflake.Init()
deltalake.Init()
transformer.Init()
webhook.Init()
batchrouter.Init()
batchrouter.Init2()
asyncdestinationmanager.Init()
batchrouterutils.Init()
dedup.Init()
event_schema.Init()
event_schema.Init2()
stash.Init()
transformationdebugger.Init()
processor.Init()
kafka.Init()
customdestinationmanager.Init()
routertransformer.Init()
router.Init()
router.Init2()
operationmanager.Init()
operationmanager.Init2()
ratelimiter.Init()
sourcedebugger.Init()
gateway.Init()
apphandlers.Init()
apphandlers.Init2()
rruntime.Init()
integrations.Init()
alert.Init()
oauth.Init()
Init()
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
cancel()
}()
Run(ctx)
}
func Run(ctx context.Context) {
runAllInit()
options := app.LoadOptions()
if options.VersionFlag {
printVersion()
return
}
application = app.New(options)
//application & backend setup should be done before starting any new goroutines.
application.Setup()
appTypeStr := strings.ToUpper(config.GetEnv("APP_TYPE", app.EMBEDDED))
appHandler = apphandlers.GetAppHandler(application, appTypeStr, versionHandler)
version := versionInfo()
bugsnag.Configure(bugsnag.Configuration{
APIKey: config.GetEnv("BUGSNAG_KEY", ""),
ReleaseStage: config.GetEnv("GO_ENV", "development"),
// The import paths for the Go packages containing your source files
ProjectPackages: []string{"main", "github.com/rudderlabs/rudder-server"},
// more configuration options
AppType: appHandler.GetAppType(),
AppVersion: version["Version"].(string),
PanicHandler: func() {},
})
ctx = bugsnag.StartSession(ctx)
defer func() {
if r := recover(); r != nil {
defer bugsnag.AutoNotify(ctx, bugsnag.SeverityError, bugsnag.MetaData{
"GoRoutines": {
"Number": runtime.NumGoroutine(),
}})
misc.RecordAppError(fmt.Errorf("%v", r))
pkgLogger.Fatal(r)
panic(r)
}
}()
//Creating Stats Client should be done right after setting up logger and before setting up other modules.
stats.Setup()
if !enableSuppressUserFeature || application.Features().SuppressUser == nil {
pkgLogger.Info("Suppress User feature is either disabled or enterprise only. Unable to poll regulations.")
}
var configEnvHandler types.ConfigEnvI
if application.Features().ConfigEnv != nil {
configEnvHandler = application.Features().ConfigEnv.Setup()
}
backendconfig.Setup(configEnvHandler)
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
return admin.StartServer(ctx)
})
g.Go(func() error {
p := &profiler.Profiler{}
return p.StartServer(ctx)
})
misc.AppStartTime = time.Now().Unix()
//If the server is standby mode, then no major services (gateway, processor, routers...) run
if options.StandByMode {
appHandler.HandleRecovery(options)
g.Go(func() error {
return startStandbyWebHandler(ctx)
})
} else {
if canStartServer() {
appHandler.HandleRecovery(options)
g.Go(misc.WithBugsnag(func() error {
return appHandler.StartRudderCore(ctx, options)
}))
}
// initialize warehouse service after core to handle non-normal recovery modes
if appTypeStr != app.GATEWAY && canStartWarehouse() {
g.Go(misc.WithBugsnag(func() error {
return startWarehouseService(ctx, application)
}))
}
}
var ctxDoneTime time.Time
g.Go(func() error {
<-ctx.Done()
ctxDoneTime = time.Now()
return nil
})
go func() {
<-ctx.Done()
<-time.After(gracefulShutdownTimeout)
// Assume graceful shutdown failed, log remain goroutines and force kill
pkgLogger.Errorf(
"Graceful termination failed after %s, goroutine dump:\n",
gracefulShutdownTimeout,
)
fmt.Print("\n\n")
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
fmt.Print("\n\n")
application.Stop()
if logger.Log != nil {
logger.Log.Sync()
}
stats.StopRuntimeStats()
if config.GetEnvAsBool("RUDDER_GRACEFUL_SHUTDOWN_TIMEOUT_EXIT", true) == true {
os.Exit(1)
}
}()
err := g.Wait()
if err != nil && err != context.Canceled {
pkgLogger.Error(err)
}
application.Stop()
pkgLogger.Infof(
"Graceful terminal after %s, with %d go-routines",
time.Since(ctxDoneTime),
runtime.NumGoroutine(),
)
// clearing zap Log buffer to std output
if logger.Log != nil {
logger.Log.Sync()
}
stats.StopRuntimeStats()
}
func startStandbyWebHandler(ctx context.Context) error {
webPort := getWebPort()
srvMux := mux.NewRouter()
srvMux.HandleFunc("/health", standbyHealthHandler)
srvMux.HandleFunc("/", standbyHealthHandler)
srvMux.HandleFunc("/version", versionHandler)
// route everything else to defaultHandler:
srvMux.PathPrefix("/").HandlerFunc(standbyDefaultHandler)
srv := &http.Server{
Addr: ":" + strconv.Itoa(webPort),
Handler: bugsnag.Handler(srvMux),
ReadTimeout: ReadTimeout,
ReadHeaderTimeout: ReadHeaderTimeout,
WriteTimeout: WriteTimeout,
IdleTimeout: IdleTimeout,
MaxHeaderBytes: MaxHeaderBytes,
}
func() {
<-ctx.Done()
srv.Shutdown(context.Background())
}()
if err := srv.ListenAndServe(); err != nil {
return fmt.Errorf("web server: %w", err)
}
return nil
}
func getWebPort() int {
appTypeStr := strings.ToUpper(config.GetEnv("APP_TYPE", app.EMBEDDED))
switch appTypeStr {
case app.GATEWAY:
return config.GetInt("Gateway.webPort", 8080)
case app.PROCESSOR:
return config.GetInt("Processor.webPort", 8086)
case app.EMBEDDED:
return config.GetInt("Gateway.webPort", 8080)
}
panic(errors.New("invalid app type"))
}
//StandbyHealthHandler is the http handler for health endpoint
func standbyHealthHandler(w http.ResponseWriter, r *http.Request) {
appTypeStr := strings.ToUpper(config.GetEnv("APP_TYPE", app.EMBEDDED))
healthVal := fmt.Sprintf(`{"appType": "%s", "mode":"%s"}`, appTypeStr, strings.ToUpper(db.CurrentMode))
w.Write([]byte(healthVal))
}
//StandbyDefaultHandler is the http handler for health endpoint
func standbyDefaultHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Server is in standby mode. Please retry after sometime", 500)
}