forked from pioro/oracle-db-appdev-monitoring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
163 lines (140 loc) · 6.26 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
// Copyright (c) 2021, 2023, Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
// Portions Copyright (c) 2016 Seth Miller <[email protected]>
package main
import (
"context"
"net/http"
"os"
"runtime/debug"
"syscall"
"time"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/version"
"github.com/prometheus/exporter-toolkit/web"
webflag "github.com/prometheus/exporter-toolkit/web/kingpinflag"
"github.com/alecthomas/kingpin/v2"
"github.com/prometheus/common/promlog"
"github.com/prometheus/common/promlog/flag"
// Required for debugging
// _ "net/http/pprof"
"github.com/oracle/oracle-db-appdev-monitoring/collector"
"github.com/oracle/oracle-db-appdev-monitoring/vault"
)
var (
// Version will be set at build time.
Version = "0.0.0.dev"
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", "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")).Int()
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()
scrapeInterval = kingpin.Flag("scrape.interval", "Interval between each scrape. Default is to scrape on collect requests").Default("0s").Duration()
toolkitFlags = webflag.AddFlags(kingpin.CommandLine, ":9161")
)
func main() {
promLogConfig := &promlog.Config{}
flag.AddFlags(kingpin.CommandLine, promLogConfig)
kingpin.HelpFlag.Short('\n')
kingpin.Version(version.Print("oracledb_exporter"))
kingpin.Parse()
logger := promlog.New(promLogConfig)
user := os.Getenv("DB_USERNAME")
password := os.Getenv("DB_PASSWORD")
connectString := os.Getenv("DB_CONNECT_STRING")
vaultName, useVault := os.LookupEnv("VAULT_ID")
if useVault {
level.Info(logger).Log("msg", "VAULT_ID env var is present so using OCI Vault", "vault_name", vaultName)
password = vault.GetVaultSecret(vaultName, os.Getenv("VAULT_SECRET_NAME"))
}
freeOSMemInterval, enableFree := os.LookupEnv("FREE_INTERVAL")
if enableFree {
level.Info(logger).Log("msg", "FREE_INTERVAL env var is present, so will attempt to release OS memory", "free_interval", freeOSMemInterval)
} else {
level.Info(logger).Log("msg", "FREE_INTERVAL end var is not present, will not periodically attempt to release memory")
}
restartInterval, enableRestart := os.LookupEnv("RESTART_INTERVAL")
if enableRestart {
level.Info(logger).Log("msg", "RESTART_INTERVAL env var is present, so will restart my own process periodically", "restart_interval", restartInterval)
} else {
level.Info(logger).Log("msg", "RESTART_INTERVAL env var is not present, so will not restart myself periodically")
}
config := &collector.Config{
User: user,
Password: password,
ConnectString: connectString,
MaxOpenConns: *maxOpenConns,
MaxIdleConns: *maxIdleConns,
CustomMetrics: *customMetrics,
QueryTimeout: *queryTimeout,
DefaultMetricsFile: *defaultFileMetrics,
}
exporter, err := collector.NewExporter(logger, config)
if err != nil {
level.Error(logger).Log("msg", "unable to connect to DB", "error", err)
}
if *scrapeInterval != 0 {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go exporter.RunScheduledScrapes(ctx, *scrapeInterval)
}
prometheus.MustRegister(exporter)
prometheus.MustRegister(version.NewCollector("oracledb_exporter"))
level.Info(logger).Log("msg", "Starting oracledb_exporter", "version", version.Info())
level.Info(logger).Log("msg", "Build context", "build", version.BuildContext())
level.Info(logger).Log("msg", "Collect from: ", "metricPath", *metricPath)
opts := promhttp.HandlerOpts{
ErrorHandling: promhttp.ContinueOnError,
}
http.Handle(*metricPath, promhttp.HandlerFor(prometheus.DefaultGatherer, opts))
http.HandleFunc("/", func(w http.ResponseWriter, r *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>"))
})
// start a ticker to cause rebirth
if enableRestart {
duration, err := time.ParseDuration(restartInterval)
if err != nil {
level.Info(logger).Log("msg", "Could not parse RESTART_INTERVAL, so ignoring it")
}
ticker := time.NewTicker(duration)
defer ticker.Stop()
go func() {
<-ticker.C
level.Info(logger).Log("msg", "Restarting the process...")
executable, _ := os.Executable()
execErr := syscall.Exec(executable, os.Args, os.Environ())
if execErr != nil {
panic(execErr)
}
}()
}
// start a ticker to free OS memory
if enableFree {
duration, err := time.ParseDuration(freeOSMemInterval)
if err != nil {
level.Info(logger).Log("msg", "Could not parse FREE_INTERVAL, so ignoring it")
}
memTicker := time.NewTicker(duration)
defer memTicker.Stop()
go func() {
<-memTicker.C
level.Info(logger).Log("msg", "attempting to free OS memory")
debug.FreeOSMemory()
}()
}
server := &http.Server{}
if err := web.ListenAndServe(server, toolkitFlags, logger); err != nil {
level.Error(logger).Log("msg", "Listening error", "error", err)
os.Exit(1)
}
}
// 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
}