Skip to content

Commit f477ff2

Browse files
author
Yannig Perré
committed
Add a timeout when querying database.
Add a new option query.timeout to change timeout value (5 seconds by default).
1 parent 1131001 commit f477ff2

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

main.go

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"strconv"
1010
"time"
1111
"errors"
12+
"context"
1213

1314
"github.com/BurntSushi/toml"
1415

@@ -25,6 +26,7 @@ var (
2526
metricPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
2627
landingPage = []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>")
2728
customMetrics = flag.String("custom.metrics", os.Getenv("CUSTOM_METRICS"), "File that may contain various custom metrics in a TOML file.")
29+
queryTimeout = flag.String("query.timeout", "5", "Query timeout (in seconds).")
2830
)
2931

3032
// Metric name parts.
@@ -295,7 +297,7 @@ func (e *Exporter) scrape(ch chan<- prometheus.Metric) {
295297
if err = ScrapeMetric(e.db, ch, metric); err != nil {
296298
log.Errorln("Error scraping for", metric.Context, ":", err)
297299
e.scrapeErrors.WithLabelValues(metric.Context).Inc()
298-
}
300+
}
299301
}
300302
if err = ScrapeSessions(e.db, ch); err != nil {
301303
log.Errorln("Error scraping for sessions:", err)
@@ -416,6 +418,9 @@ func ScrapeGenericValues(db *sql.DB, ch chan<- prometheus.Metric, context string
416418
return nil
417419
}
418420
err := GeneratePrometheusMetrics(db, genericParser, request)
421+
if err != nil {
422+
return err
423+
}
419424
if !ignoreZeroResult && metricsCount == 0 {
420425
return errors.New("No metrics found while parsing")
421426
}
@@ -426,7 +431,20 @@ func ScrapeGenericValues(db *sql.DB, ch chan<- prometheus.Metric, context string
426431
// Parse SQL result and call parsing function to each row
427432
func GeneratePrometheusMetrics(db *sql.DB, parse func(row map[string]string) error, query string) error {
428433

429-
rows, err := db.Query(query) // Note: Ignoring errors for brevity
434+
// Add a timeout
435+
timeout, err := strconv.Atoi(*queryTimeout)
436+
if err != nil {
437+
log.Fatal("error while converting timeout option value: ", err)
438+
panic(err)
439+
}
440+
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
441+
defer cancel()
442+
rows, err := db.QueryContext(ctx, query)
443+
444+
if ctx.Err() == context.DeadlineExceeded {
445+
return errors.New("Oracle query timed out")
446+
}
447+
430448
if err != nil {
431449
return err
432450
}

0 commit comments

Comments
 (0)