forked from caarlos0/domain_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
157 lines (131 loc) · 4.45 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
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/alecthomas/kingpin/v2"
"github.com/caarlos0/domain_exporter/internal/client"
"github.com/caarlos0/domain_exporter/internal/collector"
"github.com/caarlos0/domain_exporter/internal/rdap"
"github.com/caarlos0/domain_exporter/internal/refresher"
"github.com/caarlos0/domain_exporter/internal/safeconfig"
"github.com/caarlos0/domain_exporter/internal/whois"
cache "github.com/patrickmn/go-cache"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// nolint: gochecknoglobals
var (
bind = kingpin.Flag("bind", "addr to bind the server").Short('b').Default(":9222").String()
debug = kingpin.Flag("debug", "show debug logs").Default("false").Bool()
format = kingpin.Flag("logFormat", "log format to use").Default("console").Enum("json", "console")
interval = kingpin.Flag("cache", "time to cache the result of whois calls").Default("2h").Duration()
timeout = kingpin.Flag("timeout", "timeout for each domain").Default("10s").Duration()
configFile = kingpin.Flag("config", "configuration file").String()
version = "dev"
)
func main() {
kingpin.Version("domain_exporter version " + version)
kingpin.HelpFlag.Short('h')
kingpin.Parse()
urlPrefix, urlPrefixOK := os.LookupEnv("DOMAIN_EXPORTER_URL_PREFIX")
if !urlPrefixOK {
urlPrefix = ""
}
zerolog.SetGlobalLevel(zerolog.InfoLevel)
if *format == "console" {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
}
if *debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
log.Debug().Msg("enabled debug mode")
}
log.Info().Msgf("starting domain_exporter %s", version)
cfg, err := safeconfig.New(*configFile)
if err != nil {
log.Fatal().Err(err).Msg("error to create config")
}
wg := &sync.WaitGroup{}
defer wg.Wait()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cache := cache.New(*interval, *interval)
cli := client.NewMultiClient(rdap.NewClient(), whois.NewClient())
cachedClient := client.NewCachedClient(cli, cache)
if len(cfg.Domains) != 0 {
wg.Add(1)
go func() {
defer wg.Done()
fresh := refresher.New(*interval, cachedClient, *timeout*time.Duration(len(cfg.Domains)), cfg.Domains...)
defer fresh.Stop()
fresh.Run(ctx)
}()
domainCollector := collector.NewDomainCollector(cachedClient, *timeout*time.Duration(len(cfg.Domains)), cfg.Domains...)
prometheus.DefaultRegisterer.MustRegister(domainCollector)
}
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/probe", probeHandler(cli))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(
w, `
<html>
<head><title>Domain Exporter</title></head>
<body>
<h1>Domain Exporter</h1>
<p><a href="%[1]s/metrics">Metrics</a></p>
<p><a href="%[1]s/probe?target=google.com">probe google.com</a></p>
</body>
</html>
`, urlPrefix,
)
})
if err := runServerWithGracefullyShutdown(wg); err != nil {
log.Fatal().Err(err).Msg("error starting server")
}
log.Info().Msg("domain exporter is finished")
}
func runServerWithGracefullyShutdown(wg *sync.WaitGroup) error {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM)
signal.Notify(signalChan, syscall.SIGINT)
server := &http.Server{Addr: *bind}
wg.Add(1)
go func() {
defer wg.Done()
sig := <-signalChan
log.Warn().Msgf("got %s signal. Shutdown", sig)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Error().Err(err).Msg("failed to shutdown http server")
}
}()
log.Info().Msgf("listening on %s", *bind)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
return err
}
return nil
}
func probeHandler(cli client.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
target := strings.TrimPrefix(params.Get("target"), "www.")
host := params.Get("host")
if target == "" {
log.Error().Msg("target parameter missing")
http.Error(w, "target parameter is missing", http.StatusBadRequest)
return
}
registry := prometheus.NewRegistry()
registry.MustRegister(collector.NewDomainCollector(cli, *timeout, safeconfig.Domain{Name: target, Host: host}))
promhttp.HandlerFor(registry, promhttp.HandlerOpts{}).ServeHTTP(w, r)
}
}