forked from iamseth/oracledb_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
295 lines (252 loc) · 9.51 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package main
import (
"bytes"
"context"
"database/sql"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime/debug"
"strings"
"time"
klogrus "github.com/go-kit/kit/log/logrus"
"github.com/kardianos/service"
"github.com/lawyzheng/daemon"
"github.com/lawyzheng/lyhook"
go_ora "github.com/sijms/go-ora/v2"
"github.com/sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/promlog"
"github.com/prometheus/common/promlog/flag"
"github.com/prometheus/exporter-toolkit/web"
"gopkg.in/alecthomas/kingpin.v2"
//Required for debugging
//_ "net/http/pprof"
)
var (
// Version will be set at build time.
Version = "0.0.0.dev"
listenAddress = kingpin.Flag("web.listen-address", "Address to listen on for web interface and telemetry. (env: LISTEN_ADDRESS)").Default(getEnv("LISTEN_ADDRESS", ":9161")).String()
metricPath = kingpin.Flag("web.telemetry-path", "Path under which to expose metrics. (env: TELEMETRY_PATH)").Default(getEnv("TELEMETRY_PATH", "/metrics")).String()
defaultFileMetrics = kingpin.Flag("default.metrics", "File with default metrics in a TOML file. (env: DEFAULT_METRICS)").Default(getEnv("DEFAULT_METRICS", filepath.Join(getCurrentPath(), "default-metrics.toml"))).String()
customMetrics = kingpin.Flag("custom.metrics", "File that may contain various custom metrics in a TOML file. (env: CUSTOM_METRICS)").Default(getEnv("CUSTOM_METRICS", "")).String()
queryTimeout = kingpin.Flag("query.timeout", "Query timeout (in seconds). (env: QUERY_TIMEOUT)").Default(getEnv("QUERY_TIMEOUT", "5")).String()
maxIdleConns = kingpin.Flag("database.maxIdleConns", "Number of maximum idle connections in the connection pool. (env: DATABASE_MAXIDLECONNS)").Default(getEnv("DATABASE_MAXIDLECONNS", "0")).Int()
maxOpenConns = kingpin.Flag("database.maxOpenConns", "Number of maximum open connections in the connection pool. (env: DATABASE_MAXOPENCONNS)").Default(getEnv("DATABASE_MAXOPENCONNS", "10")).Int()
username = kingpin.Flag("database.username", "Database username (env: DATABASE_USERNAME)").Default(getEnv("DATABASE_USERNAME", "")).String()
password = kingpin.Flag("database.password", "Database password (env: DATABASE_PASSWORD)").Default(getEnv("DATABASE_PASSWORD", "")).String()
hostname = kingpin.Flag("database.hostname", "Database hostname (env: DATABASE_HOSTNAME)").Default(getEnv("DATABASE_HOSTNAME", "")).String()
port = kingpin.Flag("database.port", "Database port (env: DATABASE_PORT)").Default(getEnv("DATABASE_PORT", "1521")).Int()
dbservice = kingpin.Flag("database.service", "Database service (env: DATABASE_SERVICE)").Default(getEnv("DATABASE_SERVICE", "")).String()
dsn = kingpin.Flag("datasource", "Database connect string (env: DATA_SOURCE_NAME)").Default(getEnv("DATA_SOURCE_NAME", "")).String()
daemonMode = kingpin.Flag("daemon", "Run as a daemon").Short('d').Bool()
silence = kingpin.Flag("silence", "Run in silence mode, only logging to file").Short('s').Bool()
scrapeInterval = kingpin.Flag("scrape.interval", "Interval between each scrape. Default is to scrape on collect requests.").Default("0s").Duration()
tlsconfigFile = kingpin.Flag("web.config", "Path to config yaml file that can enable TLS or authentication.").Default(filepath.Join(getCurrentPath(), "default-tlsconfig.yaml")).String()
serviceName = kingpin.Flag("service.name", "Name to display in service. Default is [OracleExporter]").Default("OracleExporter").String()
)
var (
panicWriter io.Writer = os.Stderr
)
// Metric name parts.
const (
namespace = "oracledb"
exporter = "exporter"
)
func panicLogger() {
if r := recover(); r != nil {
buf := new(bytes.Buffer)
buf.WriteString(fmt.Sprintf("[PANIC] %s panic: %v \n", time.Now().Format(time.RFC3339), r))
buf.Write(debug.Stack())
buf.WriteString("\n\n")
panicWriter.Write(buf.Bytes())
}
}
// getEnv returns the value of an environment variable, or returns the provided fallback value
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
func maskDsn(dsn string) string {
parts := strings.Split(dsn, "@")
if len(parts) > 1 {
maskedUrl := "***@" + parts[1]
return maskedUrl
}
return dsn
}
func connect(dsn string, logger *logrus.Logger) (*sql.DB, error) {
logger.Debug("Launching connection: ", maskDsn(dsn))
db, err := sql.Open("oracle", dsn)
if err != nil {
logger.Error("Error while connecting to", dsn)
return nil, err
}
logger.Debug("set max idle connections to ", *maxIdleConns)
db.SetMaxIdleConns(*maxIdleConns)
logger.Debug("set max open connections to ", *maxOpenConns)
db.SetMaxOpenConns(*maxOpenConns)
logger.Debug("Successfully connected to: ", maskDsn(dsn))
return db, nil
}
func ping(ctx context.Context, db *sql.DB) error {
newCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
return db.PingContext(newCtx)
}
func getCurrentPath() string {
if ex, err := os.Executable(); err == nil {
return filepath.Dir(ex)
}
return "."
}
func getLogger(config *promlog.Config) *logrus.Logger {
var formatter logrus.Formatter
if config.Format != nil && config.Format.String() == "json" {
formatter = &logrus.JSONFormatter{}
} else {
formatter = &logrus.TextFormatter{DisableColors: true}
}
logrus.SetFormatter(formatter)
f, _ := lyhook.NewRotateFile(filepath.Join(getCurrentPath(), "logs", "oracle_exporter.log"))
lyhook.SetDefaultWriter(f)
lyhook.SetFormatter(formatter)
lyhook.SetCaller(lyhook.NewDefaultCaller().SetSkip(lyhook.DefaultCallerSkip + 1))
plogger, _ := lyhook.NewRotateFile(filepath.Join(getCurrentPath(), "logs", "panic.log"))
lv := logrus.InfoLevel
if config.Level != nil {
l, err := logrus.ParseLevel(config.Level.String())
if err == nil {
lv = l
}
}
logrus.SetLevel(lv)
if *silence {
logrus.SetOutput(io.Discard)
panicWriter = plogger
} else {
panicWriter = io.MultiWriter(panicWriter, plogger)
}
return logrus.StandardLogger()
}
func main() {
promlogConfig := &promlog.Config{}
flag.AddFlags(kingpin.CommandLine, promlogConfig)
kingpin.Version("oracledb_exporter " + Version)
kingpin.HelpFlag.Short('h')
kingpin.Parse()
logger := getLogger(promlogConfig)
s := NewServer(logger)
var (
svcConfig = &service.Config{
Name: *serviceName,
DisplayName: *serviceName,
Description: "A Prometheus exporter for Oracle modeled",
WorkingDirectory: getCurrentPath(),
}
)
if *daemonMode {
envs := make(map[string]string)
if s, ok := os.LookupEnv("LISTEN_ADDRESS"); ok {
envs["LISTEN_ADDRESS"] = s
}
if s, ok := os.LookupEnv("TELEMETRY_PATH"); ok {
envs["TELEMETRY_PATH"] = s
}
if s, ok := os.LookupEnv("DEFAULT_METRICS"); ok {
envs["DEFAULT_METRICS"] = s
}
if s, ok := os.LookupEnv("CUSTOM_METRICS"); ok {
envs["CUSTOM_METRICS"] = s
}
if s, ok := os.LookupEnv("QUERY_TIMEOUT"); ok {
envs["QUERY_TIMEOUT"] = s
}
if s, ok := os.LookupEnv("DATABASE_MAXIDLECONNS"); ok {
envs["DATABASE_MAXIDLECONNS"] = s
}
if s, ok := os.LookupEnv("DATABASE_MAXOPENCONNS"); ok {
envs["DATABASE_MAXOPENCONNS"] = s
}
if s, ok := os.LookupEnv("DATA_SOURCE_NAME"); ok {
envs["DATA_SOURCE_NAME"] = s
}
var args []string
for _, arg := range os.Args[1:] {
if strings.EqualFold(arg, "--daemon") || strings.EqualFold(arg, "-d") {
continue
}
args = append(args, arg)
}
if !(*silence) {
args = append(args, "-s")
}
svcConfig.EnvVars = envs
svcConfig.Arguments = args
ctl, err := daemon.NewController(svcConfig, s)
if err != nil {
logger.Error("new daemon error: ", err)
return
}
ctl.Uninstall()
if err := ctl.Install(); err != nil {
logger.Error("install service error: ", err)
return
}
if err := ctl.Start(); err != nil {
logger.Error("start service error: ", err)
return
}
} else {
ctl, err := daemon.NewController(svcConfig, s)
if err != nil {
logger.Error("new daemon error: ", err)
return
}
if err := ctl.Run(); err != nil {
logger.Error("run application error: ", err)
return
}
}
}
func NewServer(logger *logrus.Logger) *Server {
return &Server{logger: logger}
}
type Server struct {
logger *logrus.Logger
}
func (s *Server) Run() error {
s.logger.Info("Starting oracledb_exporter " + Version)
// dsn := os.Getenv("DATA_SOURCE_NAME")
// Load default and custom metrics
reloadMetrics(s.logger)
var connstring string
if strings.TrimSpace(*dsn) != "" {
connstring = *dsn
} else {
connstring = go_ora.BuildUrl(*hostname, *port, *dbservice, *username, *password, nil)
}
exporter := NewExporter(connstring, s.logger)
prometheus.MustRegister(exporter)
go exporter.runScheduledScrapes()
// See more info on https://github.com/prometheus/client_golang/blob/master/prometheus/promhttp/http.go#L269
opts := promhttp.HandlerOpts{
ErrorHandling: promhttp.ContinueOnError,
}
http.Handle(*metricPath, promhttp.HandlerFor(prometheus.DefaultGatherer, opts))
http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("<html><head><title>Oracle DB Exporter " + Version + "</title></head><body><h1>Oracle DB Exporter " + Version + "</h1><p><a href='" + *metricPath + "'>Metrics</a></p></body></html>"))
})
s.logger.Info("Listening on", *listenAddress)
server := &http.Server{Addr: *listenAddress}
return web.ListenAndServe(server, *tlsconfigFile, klogrus.NewLogger(s.logger, klogrus.WithLevel(s.logger.GetLevel())))
}
func (s *Server) HandleError(e error) {
s.logger.Error("err: ", e)
os.Exit(1)
}