-
Notifications
You must be signed in to change notification settings - Fork 55
/
main.go
109 lines (90 loc) · 2.69 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
package main
import (
"flag"
"fmt"
"log"
"net/http"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/net/context"
"gopkg.in/tylerb/graceful.v1"
)
func main() {
log.Println("prometheus-sql starting up...")
var (
host string
port int
service string
queriesFile string
queryDir string
confFile string
tolerateInvalidQueryDirFiles bool
)
flag.StringVar(&host, "host", DefaultHost, "Host of the service.")
flag.IntVar(&port, "port", DefaultPort, "Port of the service.")
flag.StringVar(&service, "service", DefaultService, "Query of SQL agent service.")
flag.StringVar(&queriesFile, "queries", DefaultQueriesFile, "Path to file containing queries.")
flag.StringVar(&queryDir, "queryDir", DefaultQueriesDir, "Path to directory containing queries.")
flag.StringVar(&confFile, "config", DefaultConfFile, "Configuration file to define common data sources etc.")
flag.BoolVar(&tolerateInvalidQueryDirFiles, "lax", DefaultTolerateInvalidQueryDirFiles, "Tolerate invalid files in queryDir")
flag.Parse()
if service == "" {
flag.Usage()
log.Fatal("Error: URL to SQL Agent service required.")
}
if queriesFile == DefaultQueriesFile && queryDir != "" {
queriesFile = ""
}
if queriesFile != "" && queryDir != "" {
flag.Usage()
log.Fatal("Error: You can specify either -queries or -queryDir")
}
var (
err error
queries QueryList
config *Config
)
config = newConfig()
if confFile != "" {
config, err = loadConfig(confFile)
if err != nil {
log.Fatal(err)
}
}
if queryDir != "" {
queries, err = loadQueriesInDir(queryDir, config, tolerateInvalidQueryDirFiles)
} else {
queries, err = loadQueryConfig(queriesFile, config)
}
if err != nil {
log.Fatal(err)
}
if len(queries) == 0 {
log.Fatal("No queries loaded!")
}
// Wait group of queries.
wg := new(sync.WaitGroup)
wg.Add(len(queries))
// Shared context. Close the cxt.Done channel to stop the workers.
ctx, cancel := context.WithCancel(context.Background())
type contextKey string
var w *Worker
mux := http.NewServeMux()
for _, q := range queries {
// Create a new worker and start it in its own goroutine.
w = NewWorker(ctx, q)
go w.Start(service, wg)
}
// Register the handler.
mux.Handle("/metrics", promhttp.Handler())
addr := fmt.Sprintf("%s:%d", host, port)
log.Printf("* Listening on %s...", addr)
// Handles OS kill and interrupt.
graceful.Run(addr, 5*time.Second, mux)
log.Print("Canceling workers")
cancel()
log.Print("Waiting for workers to finish")
wg.Wait()
log.Println("All workers have finished, exiting!")
}