| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "flag" |
| 7 | "net/http" |
| 8 | "os" |
| 9 | "os/signal" |
| 10 | "runtime" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "syscall" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/prometheus/client_golang/prometheus" |
| 17 | "github.com/prometheus/client_golang/prometheus/collectors" |
| 18 | log "github.com/sirupsen/logrus" |
| 19 | "golang.org/x/crypto/bcrypt" |
| 20 | |
| 21 | "github.com/oliver006/redis_exporter/exporter" |
| 22 | ) |
| 23 | |
| 24 | var ( |
| 25 | /* |
| 26 | BuildVersion, BuildDate, BuildCommitSha are filled in by the build script |
| 27 | */ |
| 28 | BuildVersion = "<<< filled in by build >>>" |
| 29 | BuildDate = "<<< filled in by build >>>" |
| 30 | BuildCommitSha = "<<< filled in by build >>>" |
| 31 | ) |
| 32 | |
| 33 | func getEnv(key string, defaultVal string) string { |
| 34 | if envVal, ok := os.LookupEnv(key); ok { |
| 35 | return envVal |
| 36 | } |
| 37 | return defaultVal |
| 38 | } |
| 39 | |
| 40 | func getEnvBool(key string, defaultVal bool) bool { |
| 41 | if envVal, ok := os.LookupEnv(key); ok { |
| 42 | envBool, err := strconv.ParseBool(envVal) |
| 43 | if err == nil { |
| 44 | return envBool |
| 45 | } |
| 46 | } |
| 47 | return defaultVal |
| 48 | } |
| 49 | |
| 50 | func getEnvInt64(key string, defaultVal int64) int64 { |
| 51 | if envVal, ok := os.LookupEnv(key); ok { |
| 52 | envInt64, err := strconv.ParseInt(envVal, 10, 64) |
| 53 | if err == nil { |
| 54 | return envInt64 |
| 55 | } |
| 56 | } |
| 57 | return defaultVal |
| 58 | } |
| 59 | |
| 60 | // parseLogLevel parses a log level string and returns the corresponding logrus level |
| 61 | func parseLogLevel(level string) (log.Level, error) { |
| 62 | switch strings.ToUpper(level) { |
| 63 | case "DEBUG": |
| 64 | return log.DebugLevel, nil |
| 65 | case "INFO": |
| 66 | return log.InfoLevel, nil |
| 67 | case "WARN", "WARNING": |
| 68 | return log.WarnLevel, nil |
| 69 | case "ERROR": |
| 70 | return log.ErrorLevel, nil |
| 71 | default: |
| 72 | return log.InfoLevel, errors.New("invalid log level: " + level) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | // validateTLSClientConfig validates TLS client configuration |
| 77 | func validateTLSClientConfig(certFile, keyFile string) error { |
| 78 | if (certFile != "") != (keyFile != "") { |
| 79 | return errors.New("TLS client key file and cert file should both be present") |
| 80 | } |
| 81 | return nil |
| 82 | } |
| 83 | |
| 84 | func validateAuthParams(basicAuthPassword, basicAuthHashPassword string) error { |
| 85 | if basicAuthPassword != "" && basicAuthHashPassword != "" { |
| 86 | return errors.New("cannot set both basic auth password and basic auth hash password") |
| 87 | } |
| 88 | if basicAuthHashPassword != "" { |
| 89 | _, err := bcrypt.Cost([]byte(basicAuthHashPassword)) |
| 90 | return err |
| 91 | } |
| 92 | return nil |
| 93 | } |
| 94 | |
| 95 | // loadScripts loads Lua scripts from the provided script paths |
| 96 | func loadScripts(scriptPath string) (map[string][]byte, error) { |
| 97 | if scriptPath == "" { |
| 98 | return nil, nil |
| 99 | } |
| 100 | |
| 101 | scripts := strings.Split(scriptPath, ",") |
| 102 | ls := make(map[string][]byte, len(scripts)) |
| 103 | |
| 104 | for _, script := range scripts { |
| 105 | scriptContent, err := os.ReadFile(script) |
| 106 | if err != nil { |
| 107 | return nil, err |
| 108 | } |
| 109 | ls[script] = scriptContent |
| 110 | } |
| 111 | |
| 112 | return ls, nil |
| 113 | } |
| 114 | |
| 115 | // setupLogging configures logging based on the provided parameters |
| 116 | func setupLogging(isDebug bool, logLevel, logFormat string) error { |
| 117 | switch logFormat { |
| 118 | case "json": |
| 119 | log.SetFormatter(&log.JSONFormatter{}) |
| 120 | default: |
| 121 | log.SetFormatter(&log.TextFormatter{}) |
| 122 | } |
| 123 | |
| 124 | lvl := log.InfoLevel |
| 125 | if isDebug { |
| 126 | lvl = log.DebugLevel |
| 127 | } else { |
| 128 | parsedLvl, err := parseLogLevel(logLevel) |
| 129 | if err == nil { |
| 130 | lvl = parsedLvl |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | log.SetLevel(lvl) |
| 135 | return nil |
| 136 | } |
| 137 | |
| 138 | // createPrometheusRegistry creates and configures a Prometheus registry |
| 139 | func createPrometheusRegistry(redisMetricsOnly, inclGoRuntimeMetrics bool) *prometheus.Registry { |
| 140 | registry := prometheus.NewRegistry() |
| 141 | if !redisMetricsOnly { |
| 142 | registry.MustRegister( |
| 143 | // expose process metrics like CPU, Memory, file descriptor usage etc. |
| 144 | collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), |
| 145 | ) |
| 146 | if inclGoRuntimeMetrics { |
| 147 | registry.MustRegister( |
| 148 | // expose all Go runtime metrics like GC stats, memory stats etc. |
| 149 | collectors.NewGoCollector(collectors.WithGoCollectorRuntimeMetrics(collectors.MetricsAll)), |
| 150 | ) |
| 151 | } |
| 152 | } |
| 153 | return registry |
| 154 | } |
| 155 | |
| 156 | func main() { |
| 157 | var ( |
| 158 | redisAddr = flag.String("redis.addr", getEnv("REDIS_ADDR", "redis://localhost:6379"), "Address of the Redis instance to scrape") |
| 159 | redisUser = flag.String("redis.user", getEnv("REDIS_USER", ""), "User name to use for authentication (Redis ACL for Redis 6.0 and newer)") |
| 160 | redisPwd = flag.String("redis.password", getEnv("REDIS_PASSWORD", ""), "Password of the Redis instance to scrape") |
| 161 | redisPwdFile = flag.String("redis.password-file", getEnv("REDIS_PASSWORD_FILE", ""), "Password file of the Redis instance to scrape") |
| 162 | namespace = flag.String("namespace", getEnv("REDIS_EXPORTER_NAMESPACE", "redis"), "Namespace for metrics") |
| 163 | checkKeys = flag.String("check-keys", getEnv("REDIS_EXPORTER_CHECK_KEYS", ""), "Comma separated list of key-patterns to export value and length/size, searched for with SCAN") |
| 164 | checkSingleKeys = flag.String("check-single-keys", getEnv("REDIS_EXPORTER_CHECK_SINGLE_KEYS", ""), "Comma separated list of single keys to export value and length/size") |
| 165 | checkKeyGroups = flag.String("check-key-groups", getEnv("REDIS_EXPORTER_CHECK_KEY_GROUPS", ""), "Comma separated list of lua regex for grouping keys") |
| 166 | checkStreams = flag.String("check-streams", getEnv("REDIS_EXPORTER_CHECK_STREAMS", ""), "Comma separated list of stream-patterns to export info about streams, groups and consumers, searched for with SCAN") |
| 167 | checkSingleStreams = flag.String("check-single-streams", getEnv("REDIS_EXPORTER_CHECK_SINGLE_STREAMS", ""), "Comma separated list of single streams to export info about streams, groups and consumers") |
| 168 | streamsExcludeConsumerMetrics = flag.Bool("streams-exclude-consumer-metrics", getEnvBool("REDIS_EXPORTER_STREAMS_EXCLUDE_CONSUMER_METRICS", false), "Don't collect per consumer metrics for streams (decreases cardinality)") |
| 169 | countKeys = flag.String("count-keys", getEnv("REDIS_EXPORTER_COUNT_KEYS", ""), "Comma separated list of patterns to count (eg: 'db0=production_*,db3=sessions:*'), searched for with SCAN") |
| 170 | checkKeysBatchSize = flag.Int64("check-keys-batch-size", getEnvInt64("REDIS_EXPORTER_CHECK_KEYS_BATCH_SIZE", 1000), "Approximate number of keys to process in each execution, larger value speeds up scanning.\nWARNING: Still Redis is a single-threaded app, huge COUNT can affect production environment.") |
| 171 | scriptPath = flag.String("script", getEnv("REDIS_EXPORTER_SCRIPT", ""), "Comma separated list of path(s) to Redis Lua script(s) for gathering extra metrics") |
| 172 | luaScriptReadOnly = flag.Bool("lua-script-read-only", getEnvBool("REDIS_EXPORTER_LUA_SCRIPT_READ_ONLY", false), "Use EVAL_RO command for gathering extra metrics with Lua script") |
| 173 | listenAddress = flag.String("web.listen-address", getEnv("REDIS_EXPORTER_WEB_LISTEN_ADDRESS", ":9121"), "Address to listen on for web interface and telemetry.") |
| 174 | metricPath = flag.String("web.telemetry-path", getEnv("REDIS_EXPORTER_WEB_TELEMETRY_PATH", "/metrics"), "Path under which to expose metrics.") |
| 175 | configCommand = flag.String("config-command", getEnv("REDIS_EXPORTER_CONFIG_COMMAND", "CONFIG"), "What to use for the CONFIG command, set to \"-\" to skip config metrics extraction") |
| 176 | connectionTimeout = flag.String("connection-timeout", getEnv("REDIS_EXPORTER_CONNECTION_TIMEOUT", "15s"), "Timeout for connection to Redis instance") |
| 177 | tlsClientKeyFile = flag.String("tls-client-key-file", getEnv("REDIS_EXPORTER_TLS_CLIENT_KEY_FILE", ""), "Name of the client key file (including full path) if the server requires TLS client authentication") |
| 178 | tlsClientCertFile = flag.String("tls-client-cert-file", getEnv("REDIS_EXPORTER_TLS_CLIENT_CERT_FILE", ""), "Name of the client certificate file (including full path) if the server requires TLS client authentication") |
| 179 | tlsCaCertFile = flag.String("tls-ca-cert-file", getEnv("REDIS_EXPORTER_TLS_CA_CERT_FILE", ""), "Name of the CA certificate file (including full path) if the server requires TLS client authentication") |
| 180 | tlsServerKeyFile = flag.String("tls-server-key-file", getEnv("REDIS_EXPORTER_TLS_SERVER_KEY_FILE", ""), "Name of the server key file (including full path) if the web interface and telemetry should use TLS") |
| 181 | tlsServerCertFile = flag.String("tls-server-cert-file", getEnv("REDIS_EXPORTER_TLS_SERVER_CERT_FILE", ""), "Name of the server certificate file (including full path) if the web interface and telemetry should use TLS") |
| 182 | tlsServerCaCertFile = flag.String("tls-server-ca-cert-file", getEnv("REDIS_EXPORTER_TLS_SERVER_CA_CERT_FILE", ""), "Name of the CA certificate file (including full path) if the web interface and telemetry should require TLS client authentication") |
| 183 | tlsServerMinVersion = flag.String("tls-server-min-version", getEnv("REDIS_EXPORTER_TLS_SERVER_MIN_VERSION", "TLS1.2"), "Minimum TLS version that is acceptable by the web interface and telemetry when using TLS") |
| 184 | maxDistinctKeyGroups = flag.Int64("max-distinct-key-groups", getEnvInt64("REDIS_EXPORTER_MAX_DISTINCT_KEY_GROUPS", 100), "The maximum number of distinct key groups with the most memory utilization to present as distinct metrics per database, the leftover key groups will be aggregated in the 'overflow' bucket") |
| 185 | isDebug = flag.Bool("debug", getEnvBool("REDIS_EXPORTER_DEBUG", false), "Output verbose debug information (sets log level to DEBUG, takes precedence over \"--log-level\")") |
| 186 | logLevel = flag.String("log-level", getEnv("REDIS_EXPORTER_LOG_LEVEL", "INFO"), "Set log level") |
| 187 | logFormat = flag.String("log-format", getEnv("REDIS_EXPORTER_LOG_FORMAT", "txt"), "Log format, valid options are txt and json") |
| 188 | setClientName = flag.Bool("set-client-name", getEnvBool("REDIS_EXPORTER_SET_CLIENT_NAME", true), "Whether to set client name to redis_exporter") |
| 189 | isTile38 = flag.Bool("is-tile38", getEnvBool("REDIS_EXPORTER_IS_TILE38", false), "Whether to scrape Tile38 specific metrics") |
| 190 | isCluster = flag.Bool("is-cluster", getEnvBool("REDIS_EXPORTER_IS_CLUSTER", false), "Whether this is a redis cluster (Enable this if you need to fetch key level data on a Redis Cluster).") |
| 191 | clusterDiscoverHostnames = flag.Bool("cluster-discover-hostnames", getEnvBool("REDIS_EXPORTER_CLUSTER_DISCOVER_HOSTNAMES", false), "Whether to use hostname for cluster node discovery if available via `/discover-cluster-nodes` endpoint.") |
| 192 | exportClientList = flag.Bool("export-client-list", getEnvBool("REDIS_EXPORTER_EXPORT_CLIENT_LIST", false), "Whether to scrape Client List specific metrics") |
| 193 | exportClientPort = flag.Bool("export-client-port", getEnvBool("REDIS_EXPORTER_EXPORT_CLIENT_PORT", false), "Whether to include the client's port when exporting the client list. Warning: including the port increases the number of metrics generated and will make your Prometheus server take up more memory") |
| 194 | showVersion = flag.Bool("version", false, "Show version information and exit") |
| 195 | redisMetricsOnly = flag.Bool("redis-only-metrics", getEnvBool("REDIS_EXPORTER_REDIS_ONLY_METRICS", false), "Whether to export only Redis metrics (omit Go process+runtime metrics)") |
| 196 | inclGoRuntimeMetrics = flag.Bool("include-go-runtime-metrics", getEnvBool("REDIS_EXPORTER_INCLUDE_GO_RUNTIME_METRICS", false), "Whether to include Go runtime metrics") |
| 197 | pingOnConnect = flag.Bool("ping-on-connect", getEnvBool("REDIS_EXPORTER_PING_ON_CONNECT", false), "Whether to ping the redis instance after connecting") |
| 198 | inclConfigMetrics = flag.Bool("include-config-metrics", getEnvBool("REDIS_EXPORTER_INCL_CONFIG_METRICS", false), "Whether to include all config settings as metrics") |
| 199 | inclModulesMetrics = flag.Bool("include-modules-metrics", getEnvBool("REDIS_EXPORTER_INCL_MODULES_METRICS", false), "Whether to collect Redis Modules metrics") |
| 200 | inclSearchIndexesMetrics = flag.Bool("include-search-indexes-metrics", getEnvBool("REDIS_EXPORTER_INCL_SEARCH_INDEXES_METRICS", false), "Whether to collect Redis Search indexes metrics") |
| 201 | inclSentinelPeerInfo = flag.Bool("include-sentinel-peer-info", getEnvBool("REDIS_EXPORTER_INCL_SENTINEL_PEER_INFO", false), "Whether to export sentinel_peer_info metrics (high cardinality)") |
| 202 | checkSearchIndexes = flag.String("check-search-indexes", getEnv("REDIS_EXPORTER_CHECK_SEARCH_INDEXES", ".*"), "Regex pattern for Redis Search indexes to export metrics from FT.INFO command") |
| 203 | disableExportingKeyValues = flag.Bool("disable-exporting-key-values", getEnvBool("REDIS_EXPORTER_DISABLE_EXPORTING_KEY_VALUES", false), "Whether to disable values of keys stored in redis as labels or not when using check-keys/check-single-key") |
| 204 | excludeLatencyHistogramMetrics = flag.Bool("exclude-latency-histogram-metrics", getEnvBool("REDIS_EXPORTER_EXCLUDE_LATENCY_HISTOGRAM_METRICS", false), "Do not try to collect latency histogram metrics") |
| 205 | redactConfigMetrics = flag.Bool("redact-config-metrics", getEnvBool("REDIS_EXPORTER_REDACT_CONFIG_METRICS", true), "Whether to redact config settings that include potentially sensitive information like passwords") |
| 206 | inclSystemMetrics = flag.Bool("include-system-metrics", getEnvBool("REDIS_EXPORTER_INCL_SYSTEM_METRICS", false), "Whether to include system metrics like e.g. redis_total_system_memory_bytes") |
| 207 | inclRdbFileSizeMetric = flag.Bool("include-rdb-file-size-metric", getEnvBool("REDIS_EXPORTER_INCL_RDB_FILE_SIZE_METRIC", false), "Whether to include RDB file size metric. Note: Requires the exporter to run on the same host as Redis with read access to the RDB directory. Will not work in remote or containerized deployments where the RDB file is not accessible.") |
| 208 | skipTLSVerification = flag.Bool("skip-tls-verification", getEnvBool("REDIS_EXPORTER_SKIP_TLS_VERIFICATION", false), "Whether to to skip TLS verification") |
| 209 | skipCheckKeysForRoleMaster = flag.Bool("skip-checkkeys-for-role-master", getEnvBool("REDIS_EXPORTER_SKIP_CHECKKEYS_FOR_ROLE_MASTER", false), "Whether to skip gathering the check-keys metrics (size, val) when the instance is of type master (reduce load on master nodes)") |
| 210 | basicAuthUsername = flag.String("basic-auth-username", getEnv("REDIS_EXPORTER_BASIC_AUTH_USERNAME", ""), "Username for basic authentication") |
| 211 | basicAuthPassword = flag.String("basic-auth-password", getEnv("REDIS_EXPORTER_BASIC_AUTH_PASSWORD", ""), "Password for basic authentication, conflicts with --basic-auth-hash-password") |
| 212 | basicAuthHashPassword = flag.String("basic-auth-hash-password", getEnv("REDIS_EXPORTER_BASIC_AUTH_HASH_PASSWORD", ""), "Hashed password for basic authentication, bcrypt format, conflicts with --basic-auth-password") |
| 213 | disableScrapeEndpoint = flag.Bool("disable-scrape-endpoint", getEnvBool("REDIS_EXPORTER_DISABLE_SCRAPE_ENDPOINT", false), "Whether to disable the /scrape endpoint") |
| 214 | inclMetricsForEmptyDatabases = flag.Bool("include-metrics-for-empty-databases", getEnvBool("REDIS_EXPORTER_INCL_METRICS_FOR_EMPTY_DATABASES", true), "Whether to emit db metrics (like db_keys) for empty databases") |
| 215 | appendInstanceRoleLabel = flag.Bool("append-instance-role-label", getEnvBool("REDIS_EXPORTER_APPEND_INSTANCE_ROLE_LABEL", false), "Whether to append 'instance_role' label to redis metrics") |
| 216 | ) |
| 217 | flag.Parse() |
| 218 | |
| 219 | if *showVersion { |
| 220 | log.SetOutput(os.Stdout) |
| 221 | } |
| 222 | log.Printf("Redis Metrics Exporter %s build date: %s sha1: %s Go: %s GOOS: %s GOARCH: %s", |
| 223 | BuildVersion, BuildDate, BuildCommitSha, |
| 224 | runtime.Version(), |
| 225 | runtime.GOOS, |
| 226 | runtime.GOARCH, |
| 227 | ) |
| 228 | if *showVersion { |
| 229 | return |
| 230 | } |
| 231 | |
| 232 | if err := setupLogging(*isDebug, *logLevel, *logFormat); err != nil { |
| 233 | log.Fatalf("Failed to setup logging: %v", err) |
| 234 | } |
| 235 | if *isDebug { |
| 236 | log.Debugln("Enabling debug output") |
| 237 | } |
| 238 | log.Infof(`Setting log level to "%s"`, log.GetLevel().String()) |
| 239 | |
| 240 | to, err := time.ParseDuration(*connectionTimeout) |
| 241 | if err != nil { |
| 242 | log.Fatalf("Couldn't parse connection timeout duration, err: %s", err) |
| 243 | } |
| 244 | |
| 245 | passwordMap := make(map[string]string) |
| 246 | if *redisPwd == "" && *redisPwdFile != "" { |
| 247 | passwordMap, err = exporter.LoadPwdFile(*redisPwdFile) |
| 248 | if err != nil { |
| 249 | log.Fatalf("Error loading redis passwords from file %s, err: %s", *redisPwdFile, err) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | ls, err := loadScripts(*scriptPath) |
| 254 | if err != nil { |
| 255 | log.Fatalf("Error loading script files: %s", err) |
| 256 | } |
| 257 | |
| 258 | registry := createPrometheusRegistry(*redisMetricsOnly, *inclGoRuntimeMetrics) |
| 259 | |
| 260 | exp, err := exporter.NewRedisExporter( |
| 261 | *redisAddr, |
| 262 | exporter.Options{ |
| 263 | User: *redisUser, |
| 264 | Password: *redisPwd, |
| 265 | PasswordMap: passwordMap, |
| 266 | Namespace: *namespace, |
| 267 | ConfigCommandName: *configCommand, |
| 268 | CheckKeys: *checkKeys, |
| 269 | CheckSingleKeys: *checkSingleKeys, |
| 270 | CheckKeysBatchSize: *checkKeysBatchSize, |
| 271 | CheckKeyGroups: *checkKeyGroups, |
| 272 | MaxDistinctKeyGroups: *maxDistinctKeyGroups, |
| 273 | CheckStreams: *checkStreams, |
| 274 | CheckSingleStreams: *checkSingleStreams, |
| 275 | StreamsExcludeConsumerMetrics: *streamsExcludeConsumerMetrics, |
| 276 | CountKeys: *countKeys, |
| 277 | LuaScript: ls, |
| 278 | LuaScriptReadOnly: *luaScriptReadOnly, |
| 279 | InclSystemMetrics: *inclSystemMetrics, |
| 280 | InclRdbFileSizeMetric: *inclRdbFileSizeMetric, |
| 281 | InclConfigMetrics: *inclConfigMetrics, |
| 282 | DisableExportingKeyValues: *disableExportingKeyValues, |
| 283 | ExcludeLatencyHistogramMetrics: *excludeLatencyHistogramMetrics, |
| 284 | RedactConfigMetrics: *redactConfigMetrics, |
| 285 | SetClientName: *setClientName, |
| 286 | IsTile38: *isTile38, |
| 287 | IsCluster: *isCluster, |
| 288 | ClusterDiscoverHostnames: *clusterDiscoverHostnames, |
| 289 | InclModulesMetrics: *inclModulesMetrics, |
| 290 | InclSearchIndexesMetrics: *inclSearchIndexesMetrics, |
| 291 | InclSentinelPeerInfo: *inclSentinelPeerInfo, |
| 292 | CheckSearchIndexes: *checkSearchIndexes, |
| 293 | ExportClientList: *exportClientList, |
| 294 | ExportClientsInclPort: *exportClientPort, |
| 295 | SkipCheckKeysForRoleMaster: *skipCheckKeysForRoleMaster, |
| 296 | SkipTLSVerification: *skipTLSVerification, |
| 297 | ClientCertFile: *tlsClientCertFile, |
| 298 | ClientKeyFile: *tlsClientKeyFile, |
| 299 | CaCertFile: *tlsCaCertFile, |
| 300 | ConnectionTimeouts: to, |
| 301 | MetricsPath: *metricPath, |
| 302 | RedisMetricsOnly: *redisMetricsOnly, |
| 303 | PingOnConnect: *pingOnConnect, |
| 304 | RedisPwdFile: *redisPwdFile, |
| 305 | Registry: registry, |
| 306 | BuildInfo: exporter.BuildInfo{ |
| 307 | Version: BuildVersion, |
| 308 | CommitSha: BuildCommitSha, |
| 309 | Date: BuildDate, |
| 310 | }, |
| 311 | BasicAuthUsername: *basicAuthUsername, |
| 312 | BasicAuthPassword: *basicAuthPassword, |
| 313 | BasicAuthHashPassword: *basicAuthHashPassword, |
| 314 | DisableScrapeEndpoint: *disableScrapeEndpoint, |
| 315 | InclMetricsForEmptyDatabases: *inclMetricsForEmptyDatabases, |
| 316 | AppendInstanceRoleLabel: *appendInstanceRoleLabel, |
| 317 | }, |
| 318 | ) |
| 319 | if err != nil { |
| 320 | log.Fatal(err) |
| 321 | } |
| 322 | // Validate auth parameters |
| 323 | if err := validateAuthParams(*basicAuthPassword, *basicAuthHashPassword); err != nil { |
| 324 | log.Fatal(err) |
| 325 | } |
| 326 | |
| 327 | // Verify that initial client keypair and CA are accepted |
| 328 | if err := validateTLSClientConfig(*tlsClientCertFile, *tlsClientKeyFile); err != nil { |
| 329 | log.Fatal(err) |
| 330 | } |
| 331 | _, err = exp.CreateClientTLSConfig() |
| 332 | if err != nil { |
| 333 | log.Fatal(err) |
| 334 | } |
| 335 | |
| 336 | log.Infof("Providing metrics at %s%s", *listenAddress, *metricPath) |
| 337 | log.Debugf("Configured redis addr: %#v", *redisAddr) |
| 338 | server := &http.Server{ |
| 339 | Addr: *listenAddress, |
| 340 | Handler: exp, |
| 341 | } |
| 342 | go func() { |
| 343 | if *tlsServerCertFile != "" && *tlsServerKeyFile != "" { |
| 344 | log.Debugf("Bind as TLS using cert %s and key %s", *tlsServerCertFile, *tlsServerKeyFile) |
| 345 | |
| 346 | tlsConfig, err := exp.CreateServerTLSConfig(*tlsServerCertFile, *tlsServerKeyFile, *tlsServerCaCertFile, *tlsServerMinVersion) |
| 347 | if err != nil { |
| 348 | log.Fatal(err) |
| 349 | } |
| 350 | server.TLSConfig = tlsConfig |
| 351 | if err := server.ListenAndServeTLS("", ""); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 352 | log.Fatalf("TLS Server error: %v", err) |
| 353 | } |
| 354 | } else { |
| 355 | if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 356 | log.Fatalf("Server error: %v", err) |
| 357 | } |
| 358 | } |
| 359 | }() |
| 360 | |
| 361 | // graceful shutdown |
| 362 | quit := make(chan os.Signal, 1) |
| 363 | signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) |
| 364 | _quit := <-quit |
| 365 | log.Infof("Received %s signal, exiting", _quit.String()) |
| 366 | // Create a context with a timeout |
| 367 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 368 | defer cancel() |
| 369 | |
| 370 | // Shutdown the HTTP server gracefully |
| 371 | if err := server.Shutdown(ctx); err != nil { |
| 372 | log.Fatalf("Server shutdown failed: %v", err) |
| 373 | } |
| 374 | log.Infof("Server shut down gracefully") |
| 375 | } |