forked from avarabyeu/sonarqube-prometheus-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
196 lines (165 loc) · 4.96 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
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
"github.com/fleetframework/sonarqube-prometheus-exporter/pkg"
)
var (
port string
scrapeTimeout time.Duration
sonarURL string
sonarUser string
sonarPassword string
metricsNamespace string
labels map[string]string
tagKeys []string
tagSeparator string
tagExportEmpty bool
loggingLevel string
)
var (
gitRevision = "HEAD"
buildDate = "unknown"
version = "unknown"
versionCmd bool
helpCmd bool
)
//nolint:gochecknoinits
func init() {
var scrapeTimeoutStr string
var labelsStr string
var tagKeysStr string
var tagExportEmptyStr string
flag.StringVar(&port, "port", getEnv("PORT", "8080"), "Exporter port. Default 8080")
flag.StringVar(&scrapeTimeoutStr, "scrape-timeout", getEnv("SONAR_SCRAPE_TIMEOUT", "1m"), "Metrics scraper timeout. Default: 1m")
flag.StringVar(&sonarURL, "url", getEnv("SONAR_URL", ""), "Required. Sonarqube URL")
flag.StringVar(&sonarUser, "user", getEnv("SONAR_USER", ""), "Required. Sonarqube User")
flag.StringVar(&sonarPassword, "password", getEnv("SONAR_PASSWORD", ""), "Required. Sonarqube Password")
flag.StringVar(&metricsNamespace, "metrics-ns", getEnv("METRICS_NAMESPACE", "sonar"), "Prometheus metrics namespace. Default: sonar")
flag.StringVar(&labelsStr, "labels", getEnv("LABELS", ""), "Static labels to be added to all metrics. In form 'label1=labelvalue,label2=labelValue'")
flag.StringVar(&tagKeysStr, "tag-keys", getEnv("TAG_KEYS", ""), "List of tag keys to be used as metric labels")
flag.StringVar(&tagSeparator, "tag-separator", getEnv("TAG_SEPARATOR", "#"), "Tag Separator. For instance, "+
"for Sonar project with tag 'key#value', Prometheus will have label {project=\"my-project-name\"} if defined in TAG_KEYS list")
flag.StringVar(&tagExportEmptyStr, "tag-export-empty", getEnv("TAG_EXPORT_EMPTY", "TRUE"), "Export projects that does not have tags defined in 'TAG_KEYS'. "+
"Prometheus labels will be set to empty in this case")
flag.StringVar(&loggingLevel, "log", getEnv("LOGGING_LEVEL", "info"), "Logging level, e.g. debug,info. Default: debug")
flag.BoolVar(&versionCmd, "version", false, "Show version")
flag.BoolVar(&helpCmd, "help", false, "Show help")
flag.Parse()
if versionCmd {
log.Printf("Version: %s\n", version)
log.Printf("Git Revision: %s\n", gitRevision)
log.Printf("UTC Build Date: %s\n", buildDate)
os.Exit(0)
}
if helpCmd {
flag.Usage()
os.Exit(0)
}
initLogger(loggingLevel)
var err error
scrapeTimeout, err = time.ParseDuration(scrapeTimeoutStr)
if err != nil {
log.Fatalf("Unable to parse scrape duration")
}
if sonarURL == "" || sonarUser == "" || sonarPassword == "" {
flag.Usage()
log.Fatal("make sure all required flags are provided")
}
if _, err = strconv.ParseUint(port, 10, 32); err != nil {
flag.Usage()
log.Fatalf("incorrect port provided: %s", port)
}
// parses tag keys
if tagKeysStr != "" {
tagKeys = strings.Split(tagKeysStr, ",")
}
// parses tag keys
tagExportEmpty, err = strconv.ParseBool(tagExportEmptyStr)
if err != nil {
log.Fatalf("unable to parse parameter: %v", err)
}
// parses static prometheus metrics
labels, err = parseMap(labelsStr)
if err != nil {
flag.Usage()
log.Fatalf(err.Error())
}
}
func initLogger(level string) {
log.SetOutput(os.Stdout)
l, err := log.ParseLevel(level)
if err != nil {
log.Fatal()
}
log.SetLevel(l)
log.SetFormatter(&log.TextFormatter{ForceColors: true, FullTimestamp: true})
}
func main() {
// Setting up signal capturing
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
done := make(chan struct{}, 1)
go func() {
<-stop
close(done)
}()
m := http.NewServeMux()
m.Handle("/metrics", promhttp.Handler())
server := &http.Server{
Addr: ":" + port,
Handler: m,
ReadTimeout: 5 * time.Second,
}
go func() {
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}()
go func() {
sonar := pkg.NewSonarClient(sonarURL, sonarUser, sonarPassword)
err := pkg.NewCollector(sonar, tagSeparator, metricsNamespace, labels, tagKeys, tagExportEmpty).
Schedule(done, 0, scrapeTimeout)
if err != nil {
log.Fatalf("Unable to init metrics: %v", err)
}
}()
// Waiting for SIGINT (pkill -2)
<-done
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Error(err)
}
}
func getEnv(name, def string) string {
envVar := os.Getenv(name)
if envVar == "" {
envVar = def
}
return envVar
}
func parseMap(str string) (map[string]string, error) {
m := map[string]string{}
if str == "" {
return m, nil
}
entries := strings.Split(str, ",")
for _, entry := range entries {
kv := strings.SplitN(entry, "=", 2)
if len(kv) < 2 {
return nil, fmt.Errorf("incorrect format: %s", str)
}
m[kv[0]] = kv[1]
}
return m, nil
}