2020-03-16 17:03:05 +00:00
// Copyright 2013 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bufio"
2020-09-12 14:23:43 +00:00
"fmt"
2020-03-16 17:03:05 +00:00
"net"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"strconv"
"syscall"
2023-03-08 18:13:33 +00:00
"github.com/alecthomas/kingpin/v2"
2021-06-03 14:58:36 +00:00
"github.com/go-kit/log"
2020-03-16 17:03:05 +00:00
"github.com/prometheus/client_golang/prometheus"
2021-09-02 09:56:15 +00:00
"github.com/prometheus/client_golang/prometheus/promauto"
2020-03-16 17:03:05 +00:00
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/promlog"
"github.com/prometheus/common/promlog/flag"
"github.com/prometheus/common/version"
2020-04-08 18:59:19 +00:00
"github.com/prometheus/statsd_exporter/pkg/address"
2020-03-16 17:03:05 +00:00
"github.com/prometheus/statsd_exporter/pkg/event"
"github.com/prometheus/statsd_exporter/pkg/exporter"
2021-09-01 10:54:07 +00:00
"github.com/prometheus/statsd_exporter/pkg/level"
2020-07-28 15:43:02 +00:00
"github.com/prometheus/statsd_exporter/pkg/line"
2020-03-16 17:03:05 +00:00
"github.com/prometheus/statsd_exporter/pkg/listener"
"github.com/prometheus/statsd_exporter/pkg/mapper"
2021-02-07 04:27:11 +00:00
"github.com/prometheus/statsd_exporter/pkg/mappercache/lru"
"github.com/prometheus/statsd_exporter/pkg/mappercache/randomreplacement"
2021-07-21 12:46:19 +00:00
"github.com/prometheus/statsd_exporter/pkg/relay"
2020-03-16 17:03:05 +00:00
)
var (
2021-09-02 09:56:15 +00:00
eventStats = promauto . NewCounterVec (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_events_total" ,
Help : "The total number of StatsD events seen." ,
} ,
[ ] string { "type" } ,
)
2021-09-02 09:56:15 +00:00
eventsFlushed = promauto . NewCounter (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_event_queue_flushed_total" ,
Help : "Number of times events were flushed to exporter" ,
} ,
)
2021-09-02 09:56:15 +00:00
eventsUnmapped = promauto . NewCounter (
2020-04-08 18:59:19 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_events_unmapped_total" ,
Help : "The total number of StatsD events no mapping was found for." ,
} )
2021-09-02 09:56:15 +00:00
udpPackets = promauto . NewCounter (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_udp_packets_total" ,
Help : "The total number of StatsD packets received over UDP." ,
} ,
)
2021-09-02 09:56:15 +00:00
tcpConnections = promauto . NewCounter (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_tcp_connections_total" ,
Help : "The total number of TCP connections handled." ,
} ,
)
2021-09-02 09:56:15 +00:00
tcpErrors = promauto . NewCounter (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_tcp_connection_errors_total" ,
Help : "The number of errors encountered reading from TCP." ,
} ,
)
2021-09-02 09:56:15 +00:00
tcpLineTooLong = promauto . NewCounter (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_tcp_too_long_lines_total" ,
Help : "The number of lines discarded due to being too long." ,
} ,
)
2021-09-02 09:56:15 +00:00
unixgramPackets = promauto . NewCounter (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_unixgram_packets_total" ,
Help : "The total number of StatsD packets received over Unixgram." ,
} ,
)
2021-09-02 09:56:15 +00:00
linesReceived = promauto . NewCounter (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_lines_total" ,
Help : "The total number of StatsD lines received." ,
} ,
)
2021-09-02 09:56:15 +00:00
samplesReceived = promauto . NewCounter (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_samples_total" ,
Help : "The total number of StatsD samples received." ,
} ,
)
2021-09-02 09:56:15 +00:00
sampleErrors = promauto . NewCounterVec (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_sample_errors_total" ,
Help : "The total number of errors parsing StatsD samples." ,
} ,
[ ] string { "reason" } ,
)
2021-09-02 09:56:15 +00:00
tagsReceived = promauto . NewCounter (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_tags_total" ,
Help : "The total number of DogStatsD tags processed." ,
} ,
)
2021-09-02 09:56:15 +00:00
tagErrors = promauto . NewCounter (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_tag_errors_total" ,
Help : "The number of errors parsing DogStatsD tags." ,
} ,
)
2021-09-02 09:56:15 +00:00
configLoads = promauto . NewCounterVec (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_config_reloads_total" ,
Help : "The number of configuration reloads." ,
} ,
[ ] string { "outcome" } ,
)
2021-09-02 09:56:15 +00:00
mappingsCount = promauto . NewGauge ( prometheus . GaugeOpts {
2020-03-16 17:03:05 +00:00
Name : "statsd_exporter_loaded_mappings" ,
Help : "The current number of configured metric mappings." ,
} )
2021-09-02 09:56:15 +00:00
conflictingEventStats = promauto . NewCounterVec (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_events_conflict_total" ,
Help : "The total number of StatsD events with conflicting names." ,
} ,
[ ] string { "type" } ,
)
2021-09-02 09:56:15 +00:00
errorEventStats = promauto . NewCounterVec (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_events_error_total" ,
Help : "The total number of StatsD events discarded due to errors." ,
} ,
[ ] string { "reason" } ,
)
2021-09-02 09:56:15 +00:00
eventsActions = promauto . NewCounterVec (
2020-03-16 17:03:05 +00:00
prometheus . CounterOpts {
Name : "statsd_exporter_events_actions_total" ,
Help : "The total number of StatsD events by action." ,
} ,
[ ] string { "action" } ,
)
2021-09-02 09:56:15 +00:00
metricsCount = promauto . NewGaugeVec (
2020-03-16 17:03:05 +00:00
prometheus . GaugeOpts {
Name : "statsd_exporter_metrics_total" ,
Help : "The total number of metrics." ,
} ,
[ ] string { "type" } ,
)
)
2020-08-10 18:46:44 +00:00
func serveHTTP ( mux http . Handler , listenAddress string , logger log . Logger ) {
level . Error ( logger ) . Log ( "msg" , http . ListenAndServe ( listenAddress , mux ) )
2020-03-16 17:03:05 +00:00
os . Exit ( 1 )
}
2021-02-07 00:22:29 +00:00
func sighupConfigReloader ( fileName string , mapper * mapper . MetricMapper , logger log . Logger ) {
2020-03-16 17:03:05 +00:00
signals := make ( chan os . Signal , 1 )
signal . Notify ( signals , syscall . SIGHUP )
for s := range signals {
if fileName == "" {
level . Warn ( logger ) . Log ( "msg" , "Received signal but no mapping config to reload" , "signal" , s )
continue
}
2020-08-10 18:46:44 +00:00
2020-03-16 17:03:05 +00:00
level . Info ( logger ) . Log ( "msg" , "Received signal, attempting reload" , "signal" , s )
2020-08-10 18:46:44 +00:00
2021-02-07 00:22:29 +00:00
reloadConfig ( fileName , mapper , logger )
2020-08-10 18:46:44 +00:00
}
}
2021-02-07 00:22:29 +00:00
func reloadConfig ( fileName string , mapper * mapper . MetricMapper , logger log . Logger ) {
err := mapper . InitFromFile ( fileName )
2020-08-10 18:46:44 +00:00
if err != nil {
level . Info ( logger ) . Log ( "msg" , "Error reloading config" , "error" , err )
configLoads . WithLabelValues ( "failure" ) . Inc ( )
} else {
level . Info ( logger ) . Log ( "msg" , "Config reloaded successfully" )
configLoads . WithLabelValues ( "success" ) . Inc ( )
2020-03-16 17:03:05 +00:00
}
}
func dumpFSM ( mapper * mapper . MetricMapper , dumpFilename string , logger log . Logger ) error {
f , err := os . Create ( dumpFilename )
if err != nil {
return err
}
level . Info ( logger ) . Log ( "msg" , "Start dumping FSM" , "file_name" , dumpFilename )
w := bufio . NewWriter ( f )
mapper . FSM . DumpFSM ( w )
w . Flush ( )
f . Close ( )
level . Info ( logger ) . Log ( "msg" , "Finish dumping FSM" )
return nil
}
2021-02-07 00:22:29 +00:00
func getCache ( cacheSize int , cacheType string , registerer prometheus . Registerer ) ( mapper . MetricMapperCache , error ) {
var cache mapper . MetricMapperCache
var err error
if cacheSize == 0 {
2021-02-19 16:17:27 +00:00
return nil , nil
2021-02-07 00:22:29 +00:00
} else {
switch cacheType {
case "lru" :
cache , err = lru . NewMetricMapperLRUCache ( registerer , cacheSize )
case "random" :
cache , err = randomreplacement . NewMetricMapperRRCache ( registerer , cacheSize )
default :
err = fmt . Errorf ( "unsupported cache type %q" , cacheType )
}
if err != nil {
return nil , err
}
}
return cache , nil
}
2020-03-16 17:03:05 +00:00
func main ( ) {
var (
listenAddress = kingpin . Flag ( "web.listen-address" , "The address on which to expose the web interface and generated Prometheus metrics." ) . Default ( ":9102" ) . String ( )
2020-08-10 18:46:44 +00:00
enableLifecycle = kingpin . Flag ( "web.enable-lifecycle" , "Enable shutdown and reload via HTTP request." ) . Default ( "false" ) . Bool ( )
2020-03-16 17:03:05 +00:00
metricsEndpoint = kingpin . Flag ( "web.telemetry-path" , "Path under which to expose metrics." ) . Default ( "/metrics" ) . String ( )
statsdListenUDP = kingpin . Flag ( "statsd.listen-udp" , "The UDP address on which to receive statsd metric lines. \"\" disables it." ) . Default ( ":9125" ) . String ( )
statsdListenTCP = kingpin . Flag ( "statsd.listen-tcp" , "The TCP address on which to receive statsd metric lines. \"\" disables it." ) . Default ( ":9125" ) . String ( )
statsdListenUnixgram = kingpin . Flag ( "statsd.listen-unixgram" , "The Unixgram socket path to receive statsd metric lines in datagram. \"\" disables it." ) . Default ( "" ) . String ( )
2020-05-13 07:30:01 +00:00
// not using Int here because flag displays default in decimal, 0755 will show as 493
2020-03-16 17:03:05 +00:00
statsdUnixSocketMode = kingpin . Flag ( "statsd.unixsocket-mode" , "The permission mode of the unix socket." ) . Default ( "755" ) . String ( )
mappingConfig = kingpin . Flag ( "statsd.mapping-config" , "Metric mapping configuration file name." ) . String ( )
readBuffer = kingpin . Flag ( "statsd.read-buffer" , "Size (in bytes) of the operating system's transmit read buffer associated with the UDP or Unixgram connection. Please make sure the kernel parameters net.core.rmem_max is set to a value greater than the value specified." ) . Int ( )
cacheSize = kingpin . Flag ( "statsd.cache-size" , "Maximum size of your metric mapping cache. Relies on least recently used replacement policy if max size is reached." ) . Default ( "1000" ) . Int ( )
cacheType = kingpin . Flag ( "statsd.cache-type" , "Metric mapping cache type. Valid options are \"lru\" and \"random\"" ) . Default ( "lru" ) . Enum ( "lru" , "random" )
2021-07-21 12:46:19 +00:00
eventQueueSize = kingpin . Flag ( "statsd.event-queue-size" , "Size of internal queue for processing events." ) . Default ( "10000" ) . Uint ( )
2020-09-25 21:00:34 +00:00
eventFlushThreshold = kingpin . Flag ( "statsd.event-flush-threshold" , "Number of events to hold in queue before flushing." ) . Default ( "1000" ) . Int ( )
eventFlushInterval = kingpin . Flag ( "statsd.event-flush-interval" , "Maximum time between event queue flushes." ) . Default ( "200ms" ) . Duration ( )
2020-03-16 17:03:05 +00:00
dumpFSMPath = kingpin . Flag ( "debug.dump-fsm" , "The path to dump internal FSM generated for glob matching as Dot file." ) . Default ( "" ) . String ( )
2020-05-29 07:59:58 +00:00
checkConfig = kingpin . Flag ( "check-config" , "Check configuration and exit." ) . Default ( "false" ) . Bool ( )
2020-08-10 18:54:59 +00:00
dogstatsdTagsEnabled = kingpin . Flag ( "statsd.parse-dogstatsd-tags" , "Parse DogStatsd style tags. Enabled by default." ) . Default ( "true" ) . Bool ( )
influxdbTagsEnabled = kingpin . Flag ( "statsd.parse-influxdb-tags" , "Parse InfluxDB style tags. Enabled by default." ) . Default ( "true" ) . Bool ( )
libratoTagsEnabled = kingpin . Flag ( "statsd.parse-librato-tags" , "Parse Librato style tags. Enabled by default." ) . Default ( "true" ) . Bool ( )
signalFXTagsEnabled = kingpin . Flag ( "statsd.parse-signalfx-tags" , "Parse SignalFX style tags. Enabled by default." ) . Default ( "true" ) . Bool ( )
2021-07-21 12:46:19 +00:00
relayAddr = kingpin . Flag ( "statsd.relay.address" , "The UDP relay target address (host:port)" ) . String ( )
relayPacketLen = kingpin . Flag ( "statsd.relay.packet-length" , "Maximum relay output packet length to avoid fragmentation" ) . Default ( "1400" ) . Uint ( )
2020-03-16 17:03:05 +00:00
)
promlogConfig := & promlog . Config { }
flag . AddFlags ( kingpin . CommandLine , promlogConfig )
kingpin . Version ( version . Print ( "statsd_exporter" ) )
2022-09-21 21:05:42 +00:00
kingpin . CommandLine . UsageWriter ( os . Stdout )
2020-03-16 17:03:05 +00:00
kingpin . HelpFlag . Short ( 'h' )
kingpin . Parse ( )
logger := promlog . New ( promlogConfig )
2021-09-01 10:54:07 +00:00
if err := level . SetLogLevel ( promlogConfig . Level . String ( ) ) ; err != nil {
level . Error ( logger ) . Log ( "msg" , "failed to set log level" , "error" , err )
os . Exit ( 1 )
}
2021-09-02 09:56:15 +00:00
prometheus . MustRegister ( version . NewCollector ( "statsd_exporter" ) )
2020-03-16 17:03:05 +00:00
2020-08-10 16:44:23 +00:00
parser := line . NewParser ( )
if * dogstatsdTagsEnabled {
parser . EnableDogstatsdParsing ( )
}
if * influxdbTagsEnabled {
parser . EnableInfluxdbParsing ( )
}
if * libratoTagsEnabled {
parser . EnableLibratoParsing ( )
}
if * signalFXTagsEnabled {
parser . EnableSignalFXParsing ( )
}
2020-07-28 15:43:02 +00:00
2020-03-16 17:03:05 +00:00
level . Info ( logger ) . Log ( "msg" , "Starting StatsD -> Prometheus Exporter" , "version" , version . Info ( ) )
level . Info ( logger ) . Log ( "msg" , "Build context" , "context" , version . BuildContext ( ) )
events := make ( chan event . Events , * eventQueueSize )
defer close ( events )
eventQueue := event . NewEventQueue ( events , * eventFlushThreshold , * eventFlushInterval , eventsFlushed )
2021-06-07 14:00:08 +00:00
thisMapper := & mapper . MetricMapper { Registerer : prometheus . DefaultRegisterer , MappingsCount : mappingsCount , Logger : logger }
2021-02-07 00:22:29 +00:00
cache , err := getCache ( * cacheSize , * cacheType , thisMapper . Registerer )
if err != nil {
level . Error ( logger ) . Log ( "msg" , "Unable to setup metric mapper cache" , "error" , err )
os . Exit ( 1 )
}
thisMapper . UseCache ( cache )
2021-01-20 02:48:44 +00:00
if * mappingConfig != "" {
2021-02-07 00:22:29 +00:00
err := thisMapper . InitFromFile ( * mappingConfig )
2021-01-20 02:48:44 +00:00
if err != nil {
level . Error ( logger ) . Log ( "msg" , "error loading config" , "error" , err )
os . Exit ( 1 )
}
if * dumpFSMPath != "" {
2021-02-07 00:22:29 +00:00
err := dumpFSM ( thisMapper , * dumpFSMPath , logger )
2021-01-20 02:48:44 +00:00
if err != nil {
level . Error ( logger ) . Log ( "msg" , "error dumping FSM" , "error" , err )
// Failure to dump the FSM is an error (the user asked for it and it
// didn't happen) but not fatal (the exporter is fully functional
// afterwards).
}
}
}
2021-02-07 00:22:29 +00:00
exporter := exporter . NewExporter ( prometheus . DefaultRegisterer , thisMapper , logger , eventsActions , eventsUnmapped , errorEventStats , eventStats , conflictingEventStats , metricsCount )
2021-01-20 02:48:44 +00:00
if * checkConfig {
level . Info ( logger ) . Log ( "msg" , "Configuration check successful, exiting" )
return
}
2021-07-21 12:46:19 +00:00
var relayTarget * relay . Relay
if * relayAddr != "" {
var err error
relayTarget , err = relay . NewRelay ( logger , * relayAddr , * relayPacketLen )
if err != nil {
level . Error ( logger ) . Log ( "msg" , "Unable to create relay" , "err" , err )
os . Exit ( 1 )
}
}
2021-01-20 02:48:44 +00:00
level . Info ( logger ) . Log ( "msg" , "Accepting StatsD Traffic" , "udp" , * statsdListenUDP , "tcp" , * statsdListenTCP , "unixgram" , * statsdListenUnixgram )
level . Info ( logger ) . Log ( "msg" , "Accepting Prometheus Requests" , "addr" , * listenAddress )
if * statsdListenUDP == "" && * statsdListenTCP == "" && * statsdListenUnixgram == "" {
level . Error ( logger ) . Log ( "At least one of UDP/TCP/Unixgram listeners must be specified." )
os . Exit ( 1 )
}
2020-03-16 17:03:05 +00:00
if * statsdListenUDP != "" {
2020-04-08 18:59:19 +00:00
udpListenAddr , err := address . UDPAddrFromString ( * statsdListenUDP )
2020-03-16 17:03:05 +00:00
if err != nil {
level . Error ( logger ) . Log ( "msg" , "invalid UDP listen address" , "address" , * statsdListenUDP , "error" , err )
os . Exit ( 1 )
}
uconn , err := net . ListenUDP ( "udp" , udpListenAddr )
if err != nil {
level . Error ( logger ) . Log ( "msg" , "failed to start UDP listener" , "error" , err )
os . Exit ( 1 )
}
if * readBuffer != 0 {
err = uconn . SetReadBuffer ( * readBuffer )
if err != nil {
level . Error ( logger ) . Log ( "msg" , "error setting UDP read buffer" , "error" , err )
os . Exit ( 1 )
}
}
2020-04-08 18:59:19 +00:00
ul := & listener . StatsDUDPListener {
Conn : uconn ,
EventHandler : eventQueue ,
Logger : logger ,
2020-08-10 16:44:23 +00:00
LineParser : parser ,
2020-04-08 18:59:19 +00:00
UDPPackets : udpPackets ,
LinesReceived : linesReceived ,
EventsFlushed : eventsFlushed ,
2021-07-21 12:46:19 +00:00
Relay : relayTarget ,
2020-04-08 18:59:19 +00:00
SampleErrors : * sampleErrors ,
SamplesReceived : samplesReceived ,
TagErrors : tagErrors ,
TagsReceived : tagsReceived ,
}
go ul . Listen ( )
2020-03-16 17:03:05 +00:00
}
if * statsdListenTCP != "" {
2020-04-08 18:59:19 +00:00
tcpListenAddr , err := address . TCPAddrFromString ( * statsdListenTCP )
2020-03-16 17:03:05 +00:00
if err != nil {
level . Error ( logger ) . Log ( "msg" , "invalid TCP listen address" , "address" , * statsdListenUDP , "error" , err )
os . Exit ( 1 )
}
tconn , err := net . ListenTCP ( "tcp" , tcpListenAddr )
if err != nil {
level . Error ( logger ) . Log ( "msg" , err )
os . Exit ( 1 )
}
defer tconn . Close ( )
2020-04-08 18:59:19 +00:00
tl := & listener . StatsDTCPListener {
Conn : tconn ,
EventHandler : eventQueue ,
Logger : logger ,
2020-08-10 16:44:23 +00:00
LineParser : parser ,
2020-04-08 18:59:19 +00:00
LinesReceived : linesReceived ,
EventsFlushed : eventsFlushed ,
2021-07-21 12:46:19 +00:00
Relay : relayTarget ,
2020-04-08 18:59:19 +00:00
SampleErrors : * sampleErrors ,
SamplesReceived : samplesReceived ,
TagErrors : tagErrors ,
TagsReceived : tagsReceived ,
TCPConnections : tcpConnections ,
TCPErrors : tcpErrors ,
TCPLineTooLong : tcpLineTooLong ,
}
go tl . Listen ( )
2020-03-16 17:03:05 +00:00
}
if * statsdListenUnixgram != "" {
var err error
if _ , err = os . Stat ( * statsdListenUnixgram ) ; ! os . IsNotExist ( err ) {
level . Error ( logger ) . Log ( "msg" , "Unixgram socket already exists" , "socket_name" , * statsdListenUnixgram )
os . Exit ( 1 )
}
uxgconn , err := net . ListenUnixgram ( "unixgram" , & net . UnixAddr {
Net : "unixgram" ,
Name : * statsdListenUnixgram ,
} )
if err != nil {
level . Error ( logger ) . Log ( "msg" , "failed to listen on Unixgram socket" , "error" , err )
os . Exit ( 1 )
}
defer uxgconn . Close ( )
if * readBuffer != 0 {
err = uxgconn . SetReadBuffer ( * readBuffer )
if err != nil {
level . Error ( logger ) . Log ( "msg" , "error setting Unixgram read buffer" , "error" , err )
os . Exit ( 1 )
}
}
2020-04-16 16:43:27 +00:00
ul := & listener . StatsDUnixgramListener {
Conn : uxgconn ,
EventHandler : eventQueue ,
Logger : logger ,
2020-08-10 16:44:23 +00:00
LineParser : parser ,
2020-04-16 16:43:27 +00:00
UnixgramPackets : unixgramPackets ,
LinesReceived : linesReceived ,
EventsFlushed : eventsFlushed ,
2021-07-21 12:46:19 +00:00
Relay : relayTarget ,
2020-04-16 16:43:27 +00:00
SampleErrors : * sampleErrors ,
SamplesReceived : samplesReceived ,
TagErrors : tagErrors ,
TagsReceived : tagsReceived ,
}
2020-04-08 18:59:19 +00:00
go ul . Listen ( )
2020-03-16 17:03:05 +00:00
// if it's an abstract unix domain socket, it won't exist on fs
// so we can't chmod it either
if _ , err := os . Stat ( * statsdListenUnixgram ) ; ! os . IsNotExist ( err ) {
defer os . Remove ( * statsdListenUnixgram )
// convert the string to octet
perm , err := strconv . ParseInt ( "0" + string ( * statsdUnixSocketMode ) , 8 , 32 )
if err != nil {
level . Warn ( logger ) . Log ( "Bad permission %s: %v, ignoring\n" , * statsdUnixSocketMode , err )
} else {
err = os . Chmod ( * statsdListenUnixgram , os . FileMode ( perm ) )
if err != nil {
level . Warn ( logger ) . Log ( "Failed to change unixgram socket permission: %v" , err )
}
}
}
}
2021-08-16 14:23:45 +00:00
mux := http . DefaultServeMux
2020-08-10 18:46:44 +00:00
mux . Handle ( * metricsEndpoint , promhttp . Handler ( ) )
mux . HandleFunc ( "/" , func ( w http . ResponseWriter , r * http . Request ) {
w . Write ( [ ] byte ( ` < html >
< head > < title > StatsD Exporter < / title > < / head >
< body >
< h1 > StatsD Exporter < / h1 >
< p > < a href = "` + *metricsEndpoint + `" > Metrics < / a > < / p >
< / body >
< / html > ` ) )
} )
2021-01-26 18:29:23 +00:00
2021-01-28 20:22:45 +00:00
quitChan := make ( chan struct { } , 1 )
2021-01-26 18:29:23 +00:00
2020-08-10 18:46:44 +00:00
if * enableLifecycle {
mux . HandleFunc ( "/-/reload" , func ( w http . ResponseWriter , r * http . Request ) {
if r . Method == http . MethodPut || r . Method == http . MethodPost {
2021-01-26 18:29:23 +00:00
fmt . Fprintf ( w , "Requesting reload" )
2020-08-10 18:46:44 +00:00
if * mappingConfig == "" {
level . Warn ( logger ) . Log ( "msg" , "Received lifecycle api reload but no mapping config to reload" )
return
}
level . Info ( logger ) . Log ( "msg" , "Received lifecycle api reload, attempting reload" )
2021-02-07 00:22:29 +00:00
reloadConfig ( * mappingConfig , thisMapper , logger )
2020-08-10 18:46:44 +00:00
}
} )
mux . HandleFunc ( "/-/quit" , func ( w http . ResponseWriter , r * http . Request ) {
if r . Method == http . MethodPut || r . Method == http . MethodPost {
2021-01-26 18:29:23 +00:00
fmt . Fprintf ( w , "Requesting termination... Goodbye!" )
2021-01-28 20:22:45 +00:00
quitChan <- struct { } { }
2020-08-10 18:46:44 +00:00
}
} )
}
2020-10-12 10:44:00 +00:00
mux . HandleFunc ( "/-/healthy" , func ( w http . ResponseWriter , r * http . Request ) {
if r . Method == http . MethodGet {
level . Debug ( logger ) . Log ( "msg" , "Received health check" )
w . WriteHeader ( http . StatusOK )
fmt . Fprintf ( w , "Statsd Exporter is Healthy.\n" )
}
} )
mux . HandleFunc ( "/-/ready" , func ( w http . ResponseWriter , r * http . Request ) {
if r . Method == http . MethodGet {
level . Debug ( logger ) . Log ( "msg" , "Received ready check" )
w . WriteHeader ( http . StatusOK )
fmt . Fprintf ( w , "Statsd Exporter is Ready.\n" )
}
} )
2020-09-12 14:23:43 +00:00
2020-08-10 18:46:44 +00:00
go serveHTTP ( mux , * listenAddress , logger )
2021-02-07 00:22:29 +00:00
go sighupConfigReloader ( * mappingConfig , thisMapper , logger )
2020-04-08 18:59:19 +00:00
go exporter . Listen ( events )
2020-03-16 17:03:05 +00:00
2021-01-28 20:22:45 +00:00
signals := make ( chan os . Signal , 1 )
signal . Notify ( signals , os . Interrupt , syscall . SIGTERM )
// quit if we get a message on either channel
select {
case sig := <- signals :
level . Info ( logger ) . Log ( "msg" , "Received os signal, exiting" , "signal" , sig . String ( ) )
case <- quitChan :
level . Info ( logger ) . Log ( "msg" , "Received lifecycle api quit, exiting" )
}
2020-03-16 17:03:05 +00:00
}