{"record":{"id":"2b94abbee342f3eb","repo":"crowdsecurity/crowdsec","slug":"unable-to-init-database-client-w","errorCode":null,"errorMessage":"unable to init database client: %w","messagePattern":"unable to init database client: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"pkg/apiserver/apiserver.go","lineNumber":127,"sourceCode":"\n// CustomRecoveryWithWriter returns a middleware for a writer that recovers from any panics and writes a 500 if there was one.\nfunc CustomRecoveryWithWriter(c *gin.Context) {\n\tdefer recoverFromPanic(c)\n\tc.Next()\n}\n\n// NewServer creates a LAPI server.\n// It sets up a gin router, a database client, and a controller.\nfunc NewServer(ctx context.Context, config *csconfig.LocalApiServerCfg, accessLogger *log.Entry) (*APIServer, error) {\n\tvar flushScheduler gocron.Scheduler\n\n\tif accessLogger == nil {\n\t\taccessLogger = log.StandardLogger().WithFields(nil)\n\t}\n\n\tdbClient, err := database.NewClient(ctx, config.DbConfig, config.DbConfig.NewLogger())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to init database client: %w\", err)\n\t}\n\n\tif config.DbConfig.Flush != nil {\n\t\tflushScheduler, err = dbClient.StartFlushScheduler(ctx, config.DbConfig.Flush)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif !log.IsLevelEnabled(log.DebugLevel) {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\trouter := gin.New()\n\n\trouter.ForwardedByClientIP = false\n\n\t// set the remore address of the request to 127.0.0.1 if it comes from a unix socket","sourceCodeStart":109,"sourceCodeEnd":145,"githubUrl":"https://github.com/crowdsecurity/crowdsec/blob/909b5157986a2b2c2163300fdaef5ed01289f7d2/pkg/apiserver/apiserver.go#L109-L145","documentation":"NewServer fails when database.NewClient cannot open/initialize the configured DB backend (sqlite/mysql/postgres). The underlying driver error is wrapped, so the root cause is in the %w chain. It is thrown at startup of the local API server, before any HTTP handler exists.","triggerScenarios":"Calling NewServer (via initAPIServer/cscli start) with a DbConfig whose DSN/credentials are wrong, the sqlite file path is unwritable, the DB server is down, or migrations fail.","commonSituations":"Bad db_config in /etc/crowdsec/local_api_credentials.yaml or config.yaml; MySQL/Postgres host unreachable or password changed; SQLite data dir permissions; corrupted SQLite file.","solutions":["Run `cscli lapi status` or check crowdsec logs for the wrapped root cause (e.g. dial tcp refused, permission denied).","Verify db_config (type, host, port, user, password, db_path) in config.yaml.","For MySQL/Postgres, test connectivity with mysql/psql using the same credentials.","For SQLite, check the db_path directory exists and is writable by the crowdsec user.","If the DB is corrupted, restore from backup or remove and let crowdsec re-create (`cscli machines` setup will be needed again)."],"exampleFix":"// before (config.yaml)\ndb_config:\n  type: sqlite3\n  db_path: /nonexistent/crowdsec.db\n// after\ndb_config:\n  type: sqlite3\n  db_path: /var/lib/crowdsec/data/crowdsec.db","handlingStrategy":"validation","validationCode":"// before calling NewServer\nif cfg.DbConfig == nil || (cfg.DbConfig.Type == \"sqlite3\" && cfg.DbConfig.DbPath == \"\") {\n    return fmt.Errorf(\"db_config is incomplete\")\n}\nif err := pingDatabase(cfg.DbConfig); err != nil {\n    return fmt.Errorf(\"database unreachable: %w\", err)\n}","typeGuard":null,"tryCatchPattern":"srv, err := NewServer(ctx, cfg, nil)\nif err != nil {\n    if strings.Contains(err.Error(), \"unable to init database client\") {\n        log.Fatalf(\"DB config/connect problem: %v\", err)\n    }\n    return err\n}","preventionTips":["Test DB credentials with the native client before starting LAPI.","Use a managed/portable sqlite path with correct ownership.","Validate config with `cscli config show` / dry-run on deploys.","Monitor DB reachability in orchestration health checks."],"tags":["database","startup","configuration"],"backgroundTag":"database-query-failed","analyzedSha":"909b5157986a2b2c2163300fdaef5ed01289f7d2","analyzedAt":"2026-09-06T12:27:26.012Z","contentChangedAt":"2026-09-06T12:27:26.012Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}